從數組列表中建立嵌套數組樹
您有一個具有父子關係的元素數組,並希望將其轉換為嵌套數組樹。這是一個有效的解決方案:
# 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中文網其他相關文章!