I got three arrays with some kind of hierarchical predefined terms
array("fruits", "yellow", "pineapple");
array("fruits", "yellow", "lemon");
array("fruits", "red", "apple");
And I have an assoc array which has a kind of hierachy:
array('fruits'=>array('red'=>array('tomato')));
How can I push the terms of my three array at the right place that I get:
array('fruits'=>array('yellow'=>array('pineapple','lemon'),'red'=>array('tomato','apple')));
Do I use array_walk? Or array_walk_recursive? What should I use?
Best, Joerg
You convert each fruit to a nested array, then you merge using array_merge_recursive().
Here a working example (also on Codepad):
$fruits = array(
array("fruits", "yellow", "pineapple"),
array("fruits", "yellow", "lemon"),
array("fruits", "red", "apple"),
array("fruits", "red", "tomato"),
);
// Convert array to nested array
function nest($leaf)
{
if (count($leaf) > 1)
{
$key = array_shift($leaf);
return array($key => nest($leaf));
}
else
{
return $leaf;
}
}
$tree = array();
foreach($fruits as $fruit)
{
// Convert each fruit to a nested array and merge recursively
$tree = array_merge_recursive($tree, nest($fruit));
}
print_r($tree);
$fruits[] = array("fruits", "yellow", "pineapple");
$fruits[] = array("fruits", "yellow", "lemon");
$fruits[] = array("fruits", "red", "apple");
foreach($fruits as $fruit) {
$multifruit[$fruit[0]][$fruit[1]][] = $fruit[2];
}
print_r($multifruit);
/* yields:
Array
(
[fruits] => Array
(
[yellow] => Array
(
[0] => pineapple
[1] => lemon
)
[red] => Array
(
[0] => apple
)
)
)
*/
Does exactly what you want. The last []
on the left side of the assignment appends the right side rather than overwriting any existing value if any exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With