将分层的多维数组显示为嵌套列表(递归)

时间:2015-04-03 11:03:54

标签: php arrays recursion multidimensional-array

我面临这一挑战:

我需要将分层多维数组中的数据显示为嵌套列表。我想用递归来做它,因为我不知道列表可能有多少级别。这是我正在处理的数据(简化):

array (size=54)
  0 => 
    object(stdClass)[786]
      public 'term_id' => string '1' (length=3)
      public 'name' => string 'All' (length=25)
      public 'parent' => string '0' (length=3)
      public 'children' => array (size=2)
            0 => 
                object(stdClass)[785]
                  public 'term_id' => string '2' (length=3)
                  public 'name' => string 'Clothes' (length=25)
                  public 'parent' => string '1' (length=3)
                  public 'children' => (size=1)
                      0 => 
                        object(stdClass)[786]
                          public 'term_id' => string '3' (length=3)
                          public 'name' => string 'Scarves' (length=25)
                          public 'parent' => string '2' (length=3)
            1 =>
                object(stdClass)[785]
                  public 'term_id' => string '4' (length=3)
                  public 'name' => string 'Gloves' (length=25)
                  public 'parent' => string '1' (length=3) 

结果应该是与此类似的嵌套列表:

  • 所有
    • 衣服
      • 围巾
    • 食品
      • 蔬菜

在尝试了很多次之后,我构建了使用array_walk_recursive和我自己的另一个递归函数(简化):

function attachChildren($items)
{
    foreach($items as $item) {
        echo $item->name;
        if (is_array(($item->children))) {
            $this->attachChildren($item->children);
        }
    }
}

function buildTree($value, $key)
{
    echo $value->name;
    if (is_array($value->children)) {
        $this->attachChildren($value->children);
    }           
}

array_walk_recursive($sortedArray, 'buildTree');   

此解决方案的问题在于使格式正确。两个函数产生输出,我发现很难将项目排列在缩进列表中。

将此数组显示为具有多个级别的缩进列表的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

function walk($array){  
    foreach ($array as $key => $value) {
        echo "<ul>";
        if(is_array($value)){
            echo "<li>{$value['name']}</li>";

            walk($value);
        }
        echo "</ul>";
    }
}

$ar = [
        ['name' => 'All', ['name' => 'Clothes', ['name' =>'Scarves']]],
        ['name' => 'Gloves']
      ];

walk($ar);