求算法帝,如何把个一个带有父子级关系的数组,怎么把它们组成一个带等级排序的数组
$data = [
['id' => 1,'pid' => 0,'name' => '销售部'],
['id' => 2,'pid' => 0,'name' => '技术部'],
['id' => 3,'pid' => 2,'name' => '前端'],
['id' => 4,'pid' => 1,'name' => '电话销售'],
['id' => 5,'pid' => 2,'name' => '后端'],
['id' => 6,'pid' => 1,'name' => '电商销售'],
['id' => 7,'pid' => 5,'name' => 'php'],
['id' => 8,'pid' => 7,'name' => 'php子部门'],
['id' => 9,'pid' => 6,'name' => '淘宝销售'],
['id' => 10,'pid' => 4,'name' => '打电话员'],
];
实现成:
$data = [
['id' => 1,'pid' => 0,'name' => '销售部','level' => 0],
['id' => 4,'pid' => 1,'name' => '电话销售','level' => 1],
['id' => 10,'pid' => 4,'name' => '打电话员','level' =>2],
['id' => 6,'pid' => 1,'name' => '电商销售','level' => 2],
['id' => 9,'pid' => 6,'name' => '淘宝销售','level' =>1],
['id' => 2,'pid' => 0,'name' => '技术部','level' => 0],
['id' => 3,'pid' => 2,'name' => '前端','level' => 1],
['id' => 5,'pid' => 2,'name' => '后端','level' => 1],
['id' => 7,'pid' => 5,'name' => 'php','level' => 2],
['id' => 8,'pid' => 7,'name' => 'php子部门','level' => 3],
];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先获取pid 为key 对应的数组关系对
写个递归函数
调用:buildArr($a1, 0, 0);
再然后 循环获取$a1 内容就好了
首先你要明确这里面不能有循环引用,比如说 id=0 pid=1和id=1 pid=0不能同时存在,然后你就可以建立一个多叉树的森林结构,最后怎么遍历每棵树,前中后序,层次遍历什么的,很easy吧