[英]php array_walk multidimensional array
我有三個帶有某種分層預定義術語的數組
array("fruits", "yellow", "pineapple");
array("fruits", "yellow", "lemon");
array("fruits", "red", "apple");
我有一個關聯數組,它有一種層次結構:
array('fruits'=>array('red'=>array('tomato')));
如何在我得到的正確位置推送我的三個陣列的條款:
array('fruits'=>array('yellow'=>array('pineapple','lemon'),'red'=>array('tomato','apple')));
我使用array_walk嗎? 還是array_walk_recursive? 我該怎么用?
最好的,Joerg
您將每個水果轉換為嵌套數組,然后使用array_merge_recursive()進行合並。
這是一個工作示例( 也在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);
?>
在這里,您可以使用更一般的問題解決方案。 我花了一段時間,所以我希望你欣賞它:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.