Reputation: 1559
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
Upvotes: 6
Views: 6265
Reputation: 3905
<?php
$fruits[] = array("fruits", "yellow", "pineapple");
$fruits[] = array("fruits", "yellow", "lemon");
$fruits[] = array("fruits", "red", "apple");
$fruits[] = array("fruits", "blue", "small","blueberry");
$fruits[] = array("fruits", "blue", "bluefruit");
$fruits[] = array("fruits", "multicolor-fruit");
function deeper(&$multifruit, $fruit) {
if (count($fruit)>2) {
$shifted = array_shift($fruit);
deeper($multifruit[$shifted], $fruit);
return $multifruit;
} else {
return $multifruit[$fruit[0]][] = $fruit[1];
}
}
foreach($fruits as $fruit) {
deeper($multifruit, $fruit);
}
print_r($multifruit);
?>
Here you go with a more general solution of your problem. It took me a while so I hope you appreciate it :)
Upvotes: 0
Reputation: 14901
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);
Upvotes: 5
Reputation: 3905
$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.
Upvotes: 1