我有以下数组结构:
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
)
)
我想重新构造数组,以便子项列在其父项下。例如:
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
)
)
我已经搜索了之前的问题,但发现其中没有一个能够实现上述目标。
有人可以帮帮我吗?
由于
答案 0 :(得分:2)
你可以尝试
$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
)
)
答案 1 :(得分:1)