Build tree from foreach loop php - php

I have following foreach loop :
foreach($mydata as $data){
$section = $data->section;
$category = $data->category;
$item = $data->item;
}
I want to build tree like this :
- section
_ category
- items
...
For now i did like this :
$tmp = [];
$newarray = [];
foreach($mydata as $data){
$section = $data->section;
$category = $data->category;
$item = $data->item;
if( !in_array($category, $temp)){
$newarray[$section][] = $category;
}
}
// output:
Array(
[SectionName_one] => Array(
[0] => categoryOneName_one
[1] => categoryOneName_two
[2] => categoryOneName_three
)
[SectionName_two] => Array(
[0] => categoryTwoName_one
[1] => categoryTwoName_two
[2] => categoryTwoName_three
)
...
)
And i am blocked here, i don't know how to insert items elements for each category, if you hava an idea thanks to help me :)
Thank you

foreach ($mydata as $data){
$newarray[$data->section][$data->category][]= $data->item;
}
PHP is quite forgiving with non-existent array keys.

Related

push data to at the end of each value in php

I have some array like this
Array(
[0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478"}
[1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486"}
[2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486"}
)
Here i want to add some data to at the end of each looping so data will look as follow.
Array(
[0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478","variation_name"=>"tiles" ,"hsn" =>"42424"}
[1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486","variation_name"=>"wood","hsn" =>"63636"}
[2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486","variation_name"=>"granite","hsn" =>"66656"}
)
I tried array push method but its created another index , instead of adding new data to last
below is my code.
$items = array();
$variations = array();
if ($purchaseOrderDetails->getOrderItems())
{
foreach ($purchaseOrderDetails->getOrderItems() as $key => $item)
{
$items[] = strval($item);
$variations[] = strval(new InventorySetVariation($item->getIsvid()));
}
}
Utility::ajaxResponseTrue("", array("po" => strval($purchaseOrderDetails), "items" => $items, "variations" => $variations));
Here I want to merge item and variations as one array .
how can I achieve it ?
Below is the example may help you to achieve similar goals of yours
<?php
$items = array(
0 => '{"puroriid":"3902598","purorid":"3901727","iid":"3927478"}',
1 => '{"puroriid":"3902599","purorid":"3901727","iid":"3927486"}',
2 => '{"puroriid":"3902600","purorid":"3901727","iid":"3927486"}'
); //Your Items
$itmesNew = [];
foreach($items as $val)
{
$newItem = json_decode($val,true);
$newItem['variation_name'] = 'test'; //New Items Append
$newItem['hsn'] = '123'; //New Items Append
$itmesNew[] = json_encode($newItem); //Add as json
}
echo "<pre>";
print_r($itmesNew);
?>
Output
Array
(
[0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478","variation_name":"test","hsn":"123"}
[1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486","variation_name":"test","hsn":"123"}
[2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486","variation_name":"test","hsn":"123"}
)

PHP combine several arrays to one

I want to combine several arrays into one, they are the result of a form post with an unknown number of elements, eg:
$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
What i want is to make a function that takes these arrays as an input and produces a single output, like
$elements = [['id'=>53,'name'=>'fire','temp'=>500] , ['id'=>54,'name'=>'water','temp'=>500] , ['id'=>55,'name'=>'earth','temp'=>500]]
I came up with the following solution:
function atg($array) {
$result = array();
for ($i=0;$i<count(reset($array));$i++) {
$newAr = array();
foreach($array as $index => $val) {
$newAr[$index] = $array[$index][$i];
}
$result[]=$newAr;
}
return $result;
}
It can be called like
$elements = atg(['id' => $ids, 'name' => $names, 'temp' => $temps]);
And it produces the right output. To me it seems a bit overly complicated though, and I'm sure this is a common problem in PHP for form posts, combining seperate fields into a single array per item. What would be a better solution?
You can loop through all of your 3 arrays at once with array_map(). There you can just return the new array with a value of each of the 3 arrays, e.g.
$result = array_map(function($id, $name, $temp){
return ["id" => $id, "name" => $name, "temp" => $temp];
}, $ids, $names, $temps);
Use below code:-
$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
$result = [];
foreach($ids as $k=>$id){
$result[$k]['id'] = $id;
$result[$k]['name'] =$names[$k];
$result[$k]['temp'] = $temps[0];
}
echo '<pre>'; print_r($result);
output:-
Array
(
[0] => Array
(
[id] => 53
[name] => fire
[temp] => 500
)
[1] => Array
(
[id] => 54
[name] => water
[temp] => 500
)
[2] => Array
(
[id] => 55
[name] => earth
[temp] => 500
)
)
If you are ok with a destructive solution, array_shift could do the trick :
$elements = array();
while (!empty($ids)) {
$elements[] = array(
'id' => array_shift($ids),
'name' => array_shift($names),
'temp' => array_shift($temps),
);
}
If you want to make a function, using the same arguments than your example, a solution could be
function atg($array) {
$elements = array();
while (!empty($array[0])) {
$new_element = array();
foreach ($array as $key_name => $array_to_shift) {
$new_element[$key_name] = array_shit($array_to_shift);
}
$elements[] = $new_element;
}
return $elements;
}
$result[$ids]['name'] = $names[0];
$result[$ids]['temp'] = $temps[0]

Returning Php multidimensional array in WordPress

I have the following array stored in the wordpress options table and I need to get the value of each title
a:1:{s:14:"swd_line_items";a:3:{i:0;a:1:{s:5:"title";s:9:"asdfasdfa";}i:1;a:1:{s:5:"title";s:13:"asdf asdf ada";}i:2;a:1:{s:5:"title";s:29:"fffffffffffffffffffffffffffff";}}}
I've tried nested foreach loops but nothing I do seems to work. There must be a simple solution?
function swd_get_line_items() {
$line_items = get_option('line_items_array');
$items = array();
foreach( $line_items as $item => $value ) {
foreach ($value as $new => $v) {
$items[] = array(
$new => $v
);
}
}
return $line_items;
}
Hope this helps :)
$array = unserialize('a:1:{s:14:"swd_line_items";a:3:{i:0;a:1:{s:5:"title";s:9:"asdfasdfa";}i:1;a:1:{s:5:"title";s:13:"asdf asdf ada";}i:2;a:1:{s:5:"title";s:29:"fffffffffffffffffffffffffffff";}}}');
foreach($array['swd_line_items'] as $item) {
echo $item['title'];
}
get_option() perfectly unsezrializes an array so there is no need to do it as the two other answers suggested it.
Then what you have is a two dimensional array but you are perfectly browsing it with two nested foreach.
By the way here is the final output of your code:
As you can see you perfectly extracted the titles:
Array
(
[0] => Array
(
[0] => Array
(
[title] => asdfasdfa
)
)
[1] => Array
(
[1] => Array
(
[title] => asdf asdf ada
)
)
[2] => Array
(
[2] => Array
(
[title] => fffffffffffffffffffffffffffff
)
)
)
But the issue here is that you do not return this array but you return this one:
return $line_items;
Change it into
return $items;
you mean this ?
function swd_get_line_items($serialized_array)
{
$line_items = unserialize($serialized_array);
$items = array();
foreach ($line_items['swd_line_items'] as $key => $item)
{
$items[$key] = $item['title'];
}
return $items;
}

How to setup a PHP multidimensional array and declare the array keys?

I need some help setting up a PHP array. I get a little lost with multidimensional arrays.
Right now, I have an array with multiple products as follows:
If I do: print_r($products['1']); I get:
Array ( [0] => size:large [1] => color:blue [2] => material:cotton )
I can do print_r($products['2']); , etc and it will show a similar array as above.
I am trying to get it where I can do this:
echo $products['1']['color']; // the color of product 1
...and echo "blue";
I tried exploding the string and adding it to the array as follows:
$step_two = explode(":", $products['1']);
foreach( $step_two as $key => $value){
$products['1'][$key] = $value;
}
I know I'm obviously doing the explode / foreach way wrong but I wanted to post my code anyway. I hope this is enough information to help sort this out.
Try this:
foreach ($products as &$product)
{
foreach ($product as $key => $value)
{
list($attribute, $val) = explode(':',$value);
$product[$attribute] = $val;
// optional:
unset($product[$key]);
}
}
?>
Here goes a sample that will convert from your first form to your desired form (output goes below)
<?php
$a = array( '1' => array('color:blue','size:large','price:cheap'));
print_r($a);
foreach ($a as $key => $inner_array) {
foreach ($inner_array as $key2 => $attribute) {
$parts = explode(":",$attribute);
$a[$key][$parts[0]] = $parts[1];
//Optional, to remove the old values
unset($a[$key][$key2]);
}
}
print_r($a);
?>
root#xxx:/home/vinko/is# php a.php
Array
(
[1] => Array
(
[0] => color:blue
[1] => size:large
[2] => price:cheap
)
)
Array
(
[1] => Array
(
[color] => blue
[size] => large
[price] => cheap
)
)
You would be better of to build the array the right way, but to solve your problem you need to explode in the loop, something like:
foreach( $products['1'] as $value){
$step_two = explode(":", $value);
$products['1'][$step_two[0]] = $step_two[1];
}
You can wrap another foreach around it to loop over your whole $products array.
And you'd also better build a new array to avoid having both the old and the new values in your $products array.
You are right: you got the "foreach" and "explode" the wrong way around. Try something like this:
foreach($products['1'] as $param => $value) {
$kv = explode(":", $value);
if(count($kv) == 2) {
$products[$kv[0]] = $kv[1];
unset($products['1'][$param]);
}
}
This code first loops over the sub-elements of your first element, then splits each one by the colon and, if there are two parts, sets the key-value back into the array.
Note the unset line - it removes array elements like $products['1'][1] after setting products['1']['color'] to blue.
If you already have $products structured in that way, you can modifty its structure like this:
$products = array(
'1' => array(
0 => 'size:large', 1 => 'color:blue', 2 => 'material:cotton'
),
'2' => array(
0 => 'size:small', 1 => 'color:red', 2 => 'material:silk'
),
);
foreach ($products as &$product) {
$newArray = array();
foreach ($product as $item) {
list($key, $value) = explode(':', $item);
$newArray[$key] = $value;
}
$product = $newArray;
}
print_r($products);
If you don't want to overwrite original $products array, just append $newArray to another array.
<?php
$products = array();
$new_product = array();
$new_product['color'] = "blue";
$new_product['size'] = "large";
$new_product['material'] = "cotton";
$products[] = $new_product;
echo $products[0]['color'];
//print_r($products);

PHP; Iterate through an assoc. array and add together all values

I have an array that I need to 'merge' the values of, and then flatten the entire thing to not be associative. I have this working, but I was hoping to find a better way.
Here's, in essence, the array:
array (
[label] => array(
[0] => array(
key => val
)
[1] => array(
key => val
)
)
[label2] => array(
[0] => array(
key => val
)
)
What I do with this is to add all values from [0] and [1] per assoc. array and return 1 array, where the output is something like:
array (
[label] => array(
[0] => array(
key => SUM(val1+val2)
)
)
[label2] => array(
[0] => array(
key => val
)
)
I do this by:
$i = array();
foreach ($array AS $key => $val) {
$i[$key] = NULL;
foreach ($val AS $r) foreach ($r AS $k => $v) {
if (count($array[$key]) > 1) { // Add value.
$i[$key][$k] += $v;
} else { // Leave alone.
$i[$key][$k] = $v;
}
}
}
Then I flatten it into one big array by using:
$array = array();
$r = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)
);
foreach ($r as $key => $val)
$array[$key] = $val;
return $array
I think this is ugly and could be done in a much more efficient way. I just can't figure it out, and SPL confuses me; but I want to learn.
Can someone help?
I think I figured it out:
$data = array();
$RII = new RecursiveIteratorIterator(
new RecursiveArrayIterator($it)
);
foreach($RII AS $key => $val) {
$data[$RII->key()] += $RII->current();
}
$this->fullData = $data;
Did everything I needed to in less code. Does this look right?
$data = array();
$RII = new RecursiveIteratorIterator(
new RecursiveArrayIterator($it)
);
foreach($RII AS $key => $val) {
$data[$RII->key()] += $RII->current();
}
$this->fullData = $data;
Replaces both functions above. It goes through the multidimensional array without question and allows me to do what I needed to do.

Categories