Php Array push with key - php

Here is what I want to output:
Array
(
[0] => Array
(
[restriction_type_code] => CALORICONTROL
[restriction_detail_code] => 3000CAL
)
[1] => Array
(
[restriction_type_code] => GLUTENFREE
[restriction_detail_code] => NR
)
)
and my actual code looks like this:
restriction :
foreach ($restriction as $value)
{
$itemSplit = explode("||", $value);
$itemSplit1 = explode("|", $itemSplit[0]);
$itemSplit2 = explode("|", $itemSplit[0]);
$arrOrderDiet['restriction_type_code'][] = $itemSplit1 //CALORICONTROL;
$arrOrderDiet['restriction_detail_code'][] = $itemSplit2//3000CAL;
}
Im trying all the possibilities but I think i ran out of solutions.

Try this
foreach ($restriction as $value)
{
$itemSplit = explode("||", $value);
$itemSplit1 = explode("|", $itemSplit[0]);
$itemSplit2 = explode("|", $itemSplit[1]);
$arrOrderDiet[] = array('restriction_type_code' => $itemSplit1, 'restriction_detail_code' => $itemSplit2);
}
Edit:
foreach ($restriction as $value)
{
$itemSplit = explode("||", $value);
$itemSplit1 = explode("|", $itemSplit[0]);
$itemSplit2 = explode("|", $itemSplit[1]);
$arrOrderDiet[] = array('restriction_type_code' => $itemSplit1[0], 'restriction_detail_code' => $itemSplit2[2]);
}

Why do you have both indices the same in:
$itemSplit1 = explode("|", $itemSplit[0]);
$itemSplit2 = explode("|", $itemSplit[0]);
Shouldn't it be like this:
$itemSplit1 = explode("|", $itemSplit[0]);
$itemSplit2 = explode("|", $itemSplit[1]);
Plus:
$tmp['restriction_type_code'] = $itemSplit1[0];
$tmp['restriction_detail_code'] = $itemSplit2[0];
$arrOrderDiet[] = $tmp;

Related

get sum of php multidiamentional array

I am looking to store sum of all keys inside an array here is my example code
<?php
// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
foreach ($category_sale_data as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value);
$category->sale_data[$sale_key][] = $sale_value;
//$category->sale_data_sum[$sale_key][] += $sale_value;
}
// display
print_r($category);
getting this output working example -> https://3v4l.org/NAKfb#v7.0.0
Here is expected to get //$category->sale_data_sum[$sale_key][] +=
$sale_value;
I am expected output like this
stdClass Object
(
[category_name] => 32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1
[sale_data] => Array
(
[32459] => Array
(
[0] => 1500
)
[32460] => Array
(
[0] => 400
)
[32461] => Array
(
[0] => 600
)
)
[sale_data_sum] => 2500
)
Simply do this:
$category->sale_data_sum = 0; // initiate key
foreach ($category_sale_data as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value);
$category->sale_data[$sale_key][] = $sale_value;
$category->sale_data_sum += $sale_value; // add each sale value
}
$category = [ 'category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1' ];
// category_name
$result['category_name'] = $category['category_name'];
// sale_data
$splitted = preg_split('/[*,]/', $category['category_name']);
for($i = 0; $i < count($splitted); $i += 4) {
$result['sale_data'][$splitted[$i]] = $splitted[$i + 1];
}
// sale_data_sum
$result['sale_data_sum'] = array_sum($result['sale_data']);
print_r($result);
Try this
<?php
// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
foreach ($category_sale_data as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value);
$category->sale_data[$sale_key][] = $sale_value;
//$category->sale_data_sum[$sale_key][] += $sale_value;
}
function sum($carry, $item)
{
$carry += array_values($item)[0];
return $carry;
}
$a = array_reduce(array_values($category->sale_data), "sum");
var_dump($a);
Or
<?php
// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
$category->sale_data_sum = null;
foreach ($category_sale_data as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value);
$category->sale_data[$sale_key][] = $sale_value;
$category->sale_data_sum += $sale_value;
}
// display
print_r($category);

split string into array object in php

I have a string like this: "abc#gmail.com;ABC,xyz#gmail.com;XYZ" and I want to convert into array boject. How can I do that?
Below is sample
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$assignedto = explode(';', $noactivity_noassignedto);
$assignedto = array((object) array("Email" => $assignedto[0], "Name" => $assignedto[1]));
$fromadd = 'some#abc.com';
$fromname = 'somename';
/*sending mail here*/
$this->init()->setsubject($sub)->addto($assignedto)->setfrom($fromadd, $fromname)->send();
Try this code:
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$assignedto = explode(',', $noactivity_noassignedto);
foreach ($assignedto as $recipient) {
$tmp = explode(';', $recipient);
$recipients[] = (object)array("Email" => $tmp[0], "Name" => $tmp[1]);
}
$recipients = (object)$recipients;
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$elements = explode(',', $noactivity_noassignedto);
foreach ($elements as $element) {
$dummy = explode(';', $element);
$assignedto[] = (object)array("Email" => $dummy[0], "Name" => $dummy[1]);
}
You need two explode
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$assignedAll = explode(',', $noactivity_noassignedto);
// here you can put loop to send all, for now just first
$assignedto = explode(';', $assignedAll[0]);
$assignedto = array((object) array("Email" => $assignedto[0], "Name" => $assignedto[1]));
This will generate the array of objects that you want
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$assignedto = explode(',', $noactivity_noassignedto);
foreach($assignedto as $item) {
list($email, $name) = explode(';', $item);
$addresses[] = (object)['Name'=>$name, 'Email'=>$email];
}
print_r($addresses);
Result: a print_r($addresses);
Array
(
[0] => stdClass Object
(
[Name] => ABC
[Email] => abc#gmail.com
)
[1] => stdClass Object
(
[Name] => XYZ
[Email] => xyz#gmail.com
)
)
You are on the right path. explode is what you are looking for to split a string into an array.
Given
$str = "abc#gmail.com;ABC";
$arr = explode($str, ';');
$arr will be array('abc#gmail.com', 'ABC');.
I think your problem is you want to invoke this multiple times. To do this:
$str = "abc#gmail.com;ABC,def#gmail.com;DEF";
$people = explode($str, ',');
foreach ($people as $person) {
$assigned_to = explode($person, ';');
// rest of your code
}

Convert flat array with dot-delimited keys to nested array

I am trying to created nested array from flat based on its keys.
Also format of keys in original array can be changed if it will simplify task.
From :
$arr = [
'player.name' => 'Joe',
'player.lastName' => 'Snow',
'team.name' => 'Stars',
'team.picture.name' => 'Joe Snow Profile',
'team.picture.file' => 'xxx.jpg'
];
To:
$arr = [
'player' => [
'name' => 'Joe'
, 'lastName' => 'Snow'
]
,'team' => [
'name'=> 'Stars'
,'picture' => [
'name' => 'Joe Snow Profile'
, 'file' =>'xxx.jpg'
]
],
];
Here is my take on it.
It should be able to handle arbitrary depth
function unflatten($arr) {
$result = array();
foreach($arr as $key => $value) {
$keys = explode(".", $key); //potentially other separator
$lastKey = array_pop($keys);
$node = &$result;
foreach($keys as $k) {
if (!array_key_exists($k, $node))
$node[$k] = array();
$node = &$node[$k];
}
$node[$lastKey] = $value;
}
return $result;
}
Combination of iteration and recursion. Could be simplified to just iterative.
$array = [
'player.name' => 'Joe',
'player.lastName' => 'Snow',
'team.name' => 'Stars',
'team.picture.name' => 'Joe Snow Profile',
'team.picture.file' => 'xxx.jpg'
];
$newArray = array ();
foreach($array as $key=> $value) {
$temp = array ();
$keys = array_reverse (explode('.', $key));
$temp[$keys[0]] = $value;
for ($i = 1; $i < count($keys); $i++) {
$temp[$keys[$i]] = $temp;
unset ($temp [$keys [$i -1]]);
}
$newArray = array_merge_recursive($newArray,$temp);
}
var_dump($newArray );
I received this question as a test, this is my answer:
<?php
function buildArray(&$newArray, $keys, $value)
{
if (sizeof($keys) == 0) {
return $value;
} else {
$key = array_shift($keys);
if (isset($newArray[$key])) {
$value = buildArray($newArray[$key], $keys, $value);
if (is_array($value)) {
$newArray[$key] += $value;
} else {
$newArray[$key] = $value;
}
$arr = $newArray;
} else {
$arr[$key] = buildArray($newArray, $keys, $value);
}
}
return $arr;
}
$arr = [
'player.name' => 'Joe',
'player.lastName' => 'Snow',
'team.name' => 'Stars',
'team.picture.name' => 'Joe Snow Profile',
'team.picture.file' => 'xxx.jpg',
];
$newArray = [];
foreach ($arr as $key => $value) {
$explodedKey = explode(".", $key);
$temp = buildArray($newArray, $explodedKey, $value);
$newArray = array_merge($temp, $newArray);
}
print_r($newArray);
?>
You could do it like this
$newArr = [];
for ($arr as $key => $val) {
$tmp = explode ('.', $key);
if (!array_key_exists ($tmp [0], $newArray){
$newArray [$tmp [0]] = [];
}
$newArray [$tmp [0]][$tmp [1]] = $val;
}
edit:
Damn didn't saw the third level in team.
Not very generic but should work for third level ;)
$newArr = [];
for ($arr as $key => $val) {
$tmp = explode ('.', $key);
if (!array_key_exists ($tmp [0], $newArray){
$newArray [$tmp [0]] = [];
}
if (count($tmp) > 2){
if (!array_key_exists ($tmp [1], $newArray[$tmp [0]]){
$newArray [$tmp [0]][$tmp[1]] = [];
}
$newArray [$tmp [0]][$tmp [1]][$tmp [2]] = $val;
} else {
$newArray [$tmp [0]][$tmp [1]] = $val;
}
}
I think you can use something like this, for converting 2d array to nested tree. But You'll have to play with parent_id
https://github.com/denis-cto/flat-array-to-nested-tree

How to extract array Keys to String in an array PHP

I need to extract a associative array keys into a string and implode with "/" or any character/symbols.
For eg:
$array = array([key1] =>
array([key11] =>
array([key111] => 'value111',
[key112] => 'value112',
[key113] => 'value113',
),
),
);
I need an output as below array:
array([0] => 'key1/key11/key111',[1] => 'key1/key11/key112', [2] => 'key1/key11/key112');
I've edited an answer given here and came up with the following code.
function listArrayRecursive($someArray, &$outputArray, $separator = "/") {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if (!$iterator->hasChildren()) {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode($separator, $p);
$outputArray[] = $path;
}
}
}
$outputArray = array();
listArrayRecursive($array, $outputArray);
print_r($outputArray);
Input:
Array
(
[key1] => Array
(
[key11] => Array
(
[key111] => value111
[key112] => value113
[key113] => value113
)
)
)
Output:
Array
(
[0] => key1/key11/key111
[1] => key1/key11/key112
[2] => key1/key11/key113
)
Works for different depth of array:
function getKeys($array, $prefix='', $separator = '/') {
$return = array();
foreach($array as $key => $value) {
if (!is_array($value)) $return[] = $prefix . $key;
else $return = array_merge($return, getKeys($value, $prefix . $key . separator), $separator);
}
return $return;
}
$keys = getKeys($array, '', '#');
See online fiddle http://ideone.com/krU4Xn
you could do something like...
$mapArray = array();
$symbol = '/';
foreach($array as $k =>$v)
foreach($v as $k1 =>$v1)
foreach($v1 as $k2 =>$v2)
$mapArray[] = $k.$symbol.$k1.$symbol.$k2;
also this obviously only works in this particular case, if it needs to be more generic it can be done, but I think this should get you started.

create associative array from array

How can I transform
Array1
(
[0] => Some Text
[1] => Some Other Text (+£14.20)
[2] => Text Text (+£26.88)
[3] => Another One (+£68.04)
)
Into associative array like the one below:
Array2
(
[Some Text] => 0 //0 since there is no (+£val) part
[Some Other Text] => 14.20
[Text Text] => Text Text 26.88
[Another One] => 68.04
)
$newArray = array();
foreach( $oldArray as $str ) {
if( preg_match( '/^(.+)\s\(\+£([\d\.]+)\)$/', $str, $matches ) ) {
$newArray[ $matches[1] ] = (double)$matches[2];
} else {
$newArray[ $str ] = 0;
}
}
Something like this should work:
$a2 = array();
foreach ($Array1 as $a1) {
if (strpos($a1, '(') > 0) {
$text = substr($a1, 0, strpos($a1, '('));
$value = substr($a1, strpos($a1, '(')+3, strpos($a1, ')')-1);
} else {
$text = $a1;
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);
EDIT:
You can do this using explode method as well:
$a2 = array();
foreach ($Array1 as $a1) {
$a1explode = explode("(", $a1, 2);
$text = $a1explode[0];
if ($a1explode[1]) {
$value = substr($a1explode[1],3);
} else {
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);

Categories