根据父子关系重新构造数组

编程入门 行业动态 更新时间:2024-10-27 02:30:41
本文介绍了根据父子关系重新构造数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我具有以下数组结构:

Array ( [0] => Array ( [id] => 83 [parent_id] => 0 [title] => Questionnaire one ) [1] => Array ( [id] => 84 [parent_id] => 0 [title] => Questionnaire two ) [2] => Array ( [id] => 85 [parent_id] => 83 [title] => Questionnaire three ) )

我想重新构建数组,以便子项在其父项下列出。例如:

I want to re-structure the array so child items are listed under their parents. For example:

Array ( [0] => Array ( [id] => 83 [parent_id] => 0 [title] => Questionnaire one ) [1] => Array ( [id] => 85 [parent_id] => 83 [title] => Questionnaire three ) [2] => Array ( [id] => 84 [parent_id] => 0 [title] => Questionnaire two ) )

我已经搜索了先前的问题,但没有发现他们确实达到了上述要求。

I've searched previous questions but found none of them actually achieve the above.

有人可以帮我吗?

谢谢

推荐答案

您可以尝试

$array = Array( "0" => Array("id" => 83,"parent_id" => 0,"title" => "Questionnaire one"), "1" => Array("id" => 84,"parent_id" => 0,"title" => "Questionnaire two"), "2" => Array("id" => 85,"parent_id" => 83,"title" => "Questionnaire three")); $id = array_map(function ($item) {return $item["id"];}, $array); $parent = array_filter($array, function ($item){return $item['parent_id'] == 0;}); $lists = array(); foreach ($parent as $value) { $lists[] = $value ; $children = array_filter($array, function ($item) use($value) {return $item['parent_id'] == $value['id'];}); foreach($children as $kids) { $lists[] = $kids ; } } echo "<pre>"; print_r($lists);

输出

Array ( [0] => Array ( [id] => 83 [parent_id] => 0 [title] => Questionnaire one ) [1] => Array ( [id] => 85 [parent_id] => 83 [title] => Questionnaire three ) [2] => Array ( [id] => 84 [parent_id] => 0 [title] => Questionnaire two ) )

更多推荐

根据父子关系重新构造数组

本文发布于:2023-10-25 00:16:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525397.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   父子   关系

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!