Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

有谁能够帮助解释一下某位技术总监的代码。谢谢了

某天在网上与某个技术总监讨论把数组展开成客户端可用的树结构时,我提供了代码。类似于 https://stackoverflow.com/questions/4196157/create-array-tree-from-array-list
这个链接上的,但比这个链接上的要简链一些。
结果呢,这位技术总监说,4行代码就足够了。然后,也给我贴了代码:

foreach ($items as $item){
    if($item['id'] == $items[$item['id']]['id'])
        $items[$item['pid']]['son'][] = &$items[$item['id']];
}

但是,我用最简单的测试用例:

$items= [
    ['id'=>1,'pid'=>0],
    ['id'=>2,'pid'=>1],
    ['id'=>3,'pid'=>2],
    ['id'=>4,'pid'=>0],
    ['id'=>5,'pid'=>4],
    ['id'=>6,'pid'=>5],
],

却怎么也展开不成树结构。我错在哪里了?谢谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$items= [
 ['id'=>6,'pid'=>5],
 ['id'=>1,'pid'=>0],
 ['id'=>3,'pid'=>2],
 ['id'=>2,'pid'=>1],
 ['id'=>4,'pid'=>0],
 ['id'=>5,'pid'=>4],
];
$items = array_column($items,null,'id');
foreach ($items as $item){
 if($item['id'] == $items[$item['id']]['id'])
 $items[$item['pid']]['son'][] = &$items[$item['id']];
}

这样子试下。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

33 comments

47.3k users

...