这里有一些非递归代码可以让你开始(如果你还没有解决它),它将根据从电子表格加载的$rows数组构建一个树。
这个想法是每个节点都有一个名称和一个子数组。所以代码只是在步骤1中为每个人(父和子)创建一个节点,然后从下到上填写步骤2中的链接。
代码不健壮,如果$rows的行重复,列表中的顺序不正确,或者在错误的地方显示孩子和父母,则可能会产生不必要的结果!良好的生产代码需要处理这些可能性,可能是在构建树之前检查和修复$rows。
$rows = [];
$rows[] = array(0,1);
$rows[] = array(1,2);
$rows[] = array(1,3);
$rows[] = array(1,4);
$rows[] = array(2,5);
$rows[] = array(3,6);
$rows[] = array(6,7);
// Build the required tree
$tree = makeTree($rows);
print_r($tree);
function makeTree(array $rows){
//----------------------
// Step 1. Make a list of nodes
// -----------------------
// make the parent node
$nodeList =[];
$nodeList[0]['name'] = "parent:";
$nodeList[0]['Children'] = [];
// make the child nodes
foreach ($rows as $cells)
{
$nodeList[$cells[1]]['name'] = "child:".$cells[1];
$nodeList[$cells[1]]['Children'] = [];
}
//----------------------
// Step 2. link each child node to its parent node
// -----------------------
for ($n = count($rows)-1; $n>=0; $n--)
{ // do this from the bottom up
$nodeParent = &$nodeList[$rows[$n][0]];
$nodeChild = &$nodeList[$rows[$n][1]];
$nodeParent['Children'][$rows[$n][1]]= $nodeChild;
}
// pick out the parent node (which by now should have all links in place)
$tree[0] = $nodeList[0];
return($tree);
}
它输出如下,可能或不接近你需要的。
Array
(
[0] => Array
(
[name] => parent:
[Children] => Array
(
[1] => Array
(
[name] => child:1
[Children] => Array
(
[4] => Array
(
[name] => child:4
[Children] => Array
(
)
)
[3] => Array
(
[name] => child:3
[Children] => Array
(
[6] => Array
(
[name] => child:6
[Children] => Array
(
[7] => Array
(
[name] => child:7
[Children] => Array
(
)
)
)
)
)
)
[2] => Array
(
[name] => child:2
[Children] => Array
(
[5] => Array
(
[name] => child:5
[Children] => Array
(
)
)
)
)
)
)
)
)
)