php 合并数组成父子关系,php - 将电子表格解析为PHP数组并返回具有父子关系的嵌套MLM表 - SO中文参考 - www.soinside.com...
這里有一些非遞歸代碼可以讓你開始(如果你還沒有解決它),它將根據從電子表格加載的$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
(
)
)
)
)
)
)
)
)
)
總結
以上是生活随笔為你收集整理的php 合并数组成父子关系,php - 将电子表格解析为PHP数组并返回具有父子关系的嵌套MLM表 - SO中文参考 - www.soinside.com...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: biweb wms门户网站php开源建站
- 下一篇: php做一个计算日期之间天数,PHP计算