我有一个带有树数据的数组(通过父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 ) ) );
源阵列中缺少一些父母.我希望缺少父项的项目是root.结果数组:
$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中有内置函数可以做到这一点.
原文链接:https://www.f2er.com/php/134925.html我尝试了以下代码,它似乎可以按照您描述的方式准备嵌套数组:
$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);
我在为我的演示文稿Hierarchical Models in SQL and PHP编写的PHP类中编写了类似的算法,但我使用的是对象而不是普通数组.