从数组列表创建嵌套数组树
您有一个具有父子关系的元素数组,并希望将其转换为嵌套数组树。这是一个有效的解决方案:
# Create a new array indexed by parent ID $new = []; foreach ($arr as $a) { $new[$a['parentid']][] = $a; } # Start with the root node $tree = createTree($new, [$arr[0]]); # Recursive function to build the tree function createTree(&$list, $parent) { $tree = []; foreach ($parent as $l) { # If there are children, create children tree if (isset($list[$l['id']])) { $l['children'] = createTree($list, $list[$l['id']]); } # Add parent to the tree $tree[] = $l; } return $tree; }
该算法根据原始数组中的父子关系高效地构造嵌套数组树。
以上是如何从平面数组列表高效创建嵌套数组树?的详细内容。更多信息请关注PHP中文网其他相关文章!