我得到了三个具有某种层次预定义项的数组
array("fruits", "yellow", "pineapple");
array("fruits", "yellow", "lemon");
array("fruits", "red", "apple");
我有一个assoc数组,它有一种层次结构:
array('fruits'=>array('red'=>array('tomato')));
我如何将我的三个数组的项推送到我得到的正确位置:
array('fruits'=>array('yellow'=>array('pineapple','lemon'),'red'=>array('tomato','apple')));
我使用array_walk吗?还是array_walk_re草书?我应该用什么?
最佳,Joerg
将每个水果转换为嵌套数组,然后使用array_marge_recurive((进行合并。
这里有一个工作示例(也在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
)
)
)
*/
做你想做的事。赋值左侧的最后一个[]
追加右侧,而不是覆盖任何现有值(如果存在(。
<?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);
?>
给你一个更通用的问题解决方案。我花了一段时间,所以我希望你能欣赏它:(