首页 > 代码库 > 一个高效的数组转树结构的算法实现

一个高效的数组转树结构的算法实现

<?php
// authorwangbinandi@gmail.com
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);

 

一个高效的数组转树结构的算法实现