本文介绍了根据父子关系重新构造数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下数组结构:
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 ) )更多推荐
根据父子关系重新构造数组
发布评论