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

(

)

)

)

)

)

)

)

)

)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值