多维数组层次结构

时间:2017-12-18 10:29:43

标签: php arrays recursion hierarchy

我想知道如何通过标识符获取层次结构。

这是一个例子:

$inputArray = array(
        array(
            "text" => "Dir1",
            "parent_id" => "",
            "id" => "1",
            "filesize" => "109"
    ),array(
        "text" => "dir2",
        "parent_id" => "",
        "id" => "2",
        "filesize" => "88",
        "children" => array(
                "text" => "Dir3",
                "parent_id" => "2",
                "id" => "3",
                "filesize" => "",
                "children" => array(
                    "text" => "dir4",
                    "parent_id" => "3",
                    "id" => "4",
                    "filesize" => "",
                    "children" => array(
                        "text" => "dir5",
                        "parent_id" => "4",
                        "id" => "4",
                        "filesize" => ""
                    )
                )
        )
    ));

寻找这个例子:

dir3/dir4/dir5

1 个答案:

答案 0 :(得分:0)

function getText($array) {
  $save[]  = $array['text'];
  if (isset($array['children'])) {
     $save = array_merge($save, getText($array['children']));
  }
  return $save;  
}

foreach($inputArray as $x) {
     echo implode('/', getText($x)) . "\n";
}

结果

Dir1
dir2/Dir3/dir4/dir5

demo