php array_walk多维数组

时间:2011-11-26 10:04:24

标签: php multidimensional-array hierarchy

我有三个带有某种分层预定义术语的数组

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? 我该怎么用?

Best,Joerg

3 个答案:

答案 0 :(得分:3)

您将每个水果转换为嵌套数组,然后使用array_merge_recursive()进行合并。

这是一个工作示例(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);

答案 1 :(得分:1)

$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
                )

        )

)
*/

完全符合您的要求。分配左侧的最后[]附加右侧而不是覆盖任何现有值(如果存在)。

答案 2 :(得分:0)

<?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);
?>  

在这里,您可以使用更一般的问题解决方案。我花了一段时间,所以我希望你能欣赏它:)