我有一个包含树数据的数组(按父ID)。我想将其转换为多维数组。做到这一点的最佳方法是什么?是否有任何简短功能?
源数组:
$source = array( '0' => array( 'Menu' => array( 'id' => 45 'name' => 'Home' 'parent_id' => 1 ) ) '1' => array( 'Menu' => array( 'id' => 47 'name' => 'Get started' 'parent_id' => 1 ) ) '2' => array( 'Menu' => array( 'id' => 72 'name' => 'Attributes' 'parent_id' => 71 ) ) '3' => array( 'Menu' => array( 'id' => 73 'name' => 'Headings' 'parent_id' => 71 ) ) '4' => array( 'Menu' => array( 'id' => 75 'name' => 'Links' 'parent_id' => 71 ) ) '5' => array( 'Menu' => array( 'id' => 59 'name' => 'Images' 'parent_id' => 75 ) ) '6' => array( 'Menu' => array( 'id' => 65 'name' => 'Lists' 'parent_id' => 75 ) ) );
源数组中缺少某些父母。我希望缺少父项的项成为根。结果数组:
$result = array( '0' => array( 'Menu' => array( 'id' => 45 'name' => 'Home' 'parent_id' => 1 ) 'Children' => array() ) '1' => array( 'Menu' => array( 'id' => 47 'name' => 'Get started' 'parent_id' => 1 ) 'Children' => array() ) '2' => array( 'Menu' => array( 'id' => 72 'name' => 'Attributes' 'parent_id' => 71 ) 'Children' => array() ) '3' => array( 'Menu' => array( 'id' => 73 'name' => 'Headings' 'parent_id' => 71 ) 'Children' => array() ) '4' => array( 'Menu' => array( 'id' => 75 'name' => 'Links' 'parent_id' => 71 ) 'Children' => array( '0' => array( 'Menu' => array( 'id' => 59 'name' => 'Images' 'parent_id' => 75 ) 'Children' => array() ) '1' => array( 'Menu' => array( 'id' => 65 'name' => 'Lists' 'parent_id' => 75 ) 'Children' => array() ) ) ) );
更新:删除方括号。
我认为PHP中没有内置函数可以做到这一点。
我尝试了以下代码,似乎可以按照您描述的方式准备嵌套数组:
$nodes = array(); $tree = array(); foreach ($source as &$node) { $node["Children"] = array(); $id = $node["Menu"]["id"]; $parent_id = $node["Menu"]["parent_id"]; $nodes[$id] =& $node; if (array_key_exists($parent_id, $nodes)) { $nodes[$parent_id]["Children"][] =& $node; } else { $tree[] =& $node; } } var_dump($tree);
我在为演示文稿SQL和PHP中的层次模型编写的PHP类中编写了类似的算法,但是我使用的是对象而不是普通数组。