一个高效的数组转树结构的算法实现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个高效的数组转树结构的算法实现相关的知识,希望对你有一定的参考价值。
<?php // [email protected] function addNode(&$node, &$tree) { $node_id = $node[‘id‘]; if (!isset($tree[$node_id])) { $tree[$node_id] = $node; $tree[$node_id][‘sub‘] = []; $node[‘ref‘] = & $tree[$node_id]; } } function addNodeWithParent(&$node, &$nodes, &$tree) { $pid = $node[‘pid‘]; if ($pid == 0) { addNode($node, $tree); } else { $pnode = & $nodes[$pid]; if (!isset($pnode[‘ref‘])) { addNodeWithParent($pnode, $nodes, $tree); } addNode($node, $pnode[‘ref‘][‘sub‘]); } }
// 数组可以无序,必须要索引 $nodes = [ 5 => [‘id‘ => 5, ‘name‘ => ‘node5‘, ‘pid‘ => 3], 1 => [‘id‘ => 1, ‘name‘ => ‘node1‘, ‘pid‘ => 0], 2 => [‘id‘ => 2, ‘name‘ => ‘node2‘, ‘pid‘ => 0], 3 => [‘id‘ => 3, ‘name‘ => ‘node3‘, ‘pid‘ => 1], 4 => [‘id‘ => 4, ‘name‘ => ‘node4‘, ‘pid‘ => 1], 6 => [‘id‘ => 6, ‘name‘ => ‘node6‘, ‘pid‘ => 2], 7 => [‘id‘ => 7, ‘name‘ => ‘node7‘, ‘pid‘ => 2], 8 => [‘id‘ => 8, ‘name‘ => ‘node8‘, ‘pid‘ => 0], ]; $tree = []; foreach($nodes as $i => &$node) { addNodeWithParent($node, $nodes, $tree); } var_dump($tree);
以上是关于一个高效的数组转树结构的算法实现的主要内容,如果未能解决你的问题,请参考以下文章