问题
I have the following array structure:
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.
Can someone please help me with this?
Thanks
回答1:
You can try
$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);
Output
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
)
)
回答2:
You could use uksort(). Heres a DEMO.
function cmp($a, $b) {
if ($stock[$a] != $stock[$b]) return $stock[$b] - $stock[$a];
return strcmp($a, $b);
}
$a = array(5 => 'apple', 1 => 'banana', 6 => 'orange', 2 => 'kiwi');
uksort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
来源:https://stackoverflow.com/questions/12960943/re-structure-array-based-on-parent-child-relationship