我知道,聚会迟到了,但看起来很有趣......
/*
* This is a 'multiway' tree where:
* a 'parent' can have any number of 'child' nodes
* therefore the 'parent node' must look like:
* [parentId] => array()
*
* where [parentId] is the index of an array;
*/
它将从根节点开始一次插入一个节点。对于大树来说,它可能会变得非常昂贵。
工作示例位于:Viper-7.com http://viper-7.com/gqSBgc
完成工作的例程:
/**
* Insert: Find the 'parent' node
* if child not found then insert a 'node'
*
* @param array node passed by reference as the new node will be inserted
* @param integer $parentId - root Id must be the lowest value
* @param integer $childId
* @return boolean true if parentId found and processed
*/
function insertNode(&$node, $parentId, $childId) {
if (isset($node[$parentId])) { // this node will be processed
if (!isset($node[$parentId][$childId])) {
$node[$parentId][$childId] = array(); // add child node
return true;
}
return true; // end of processing
}
// check all the children of this node...
foreach($node as &$child) { // need the reference
if (insertNode($child, $parentId, $childId)) {
return true;
}
}
return false; // parentId not in the tree
}
Notes:
The node to be processed is passed by reference.
The processing will end when the 'parent' id is found
给定的输入节点列表是 'child' => 'parent' 顺序,这是不寻常的,没关系,只要记住在处理中......
处理输入数据:
$theTree = array(current($links) => array()); // root
// insert all the child nodes into the tree
foreach($links as $childId => $parentId) {
$inserted = insertNode($theTree, $parentId, $childId);
}
// output the tree
echo '<pre>', 'Children are in the same order as the input array.', '<br />';
print_r($theTree);
echo '</pre>';
需要排列输入列表,以便加载“树”,以便添加要添加的子项的父项must已经在树上了。我假设输入列表已经按要求的顺序排列
测试数据,排序并显示:
# cat_id => parent_id
$links = array(
1 => 0,
2 => 1,
3 => 2,
4 => 0,
5 => 4, // multiple children
11 => 4,
99 => 4,
13 => 11,
6 => 0
);
输出,我在原始输入中添加了一个子树......
Children are in the same order as the input array.
Array
(
[0] => Array
(
[1] => Array
(
[2] => Array
(
[3] => Array
(
)
)
)
[4] => Array
(
[5] => Array
(
)
[11] => Array
(
[13] => Array
(
)
)
[99] => Array
(
)
)
[6] => Array
(
)
)
)