我有数组并希望使用_level和_parent对数组进行分组,然后_id将进行排序,以便输出显示:
array(
'163' => array (
"desc" => "master array",
"_id" => 163,
"_parent" => null,
"_level" => 1,
),
'172' => array (
"desc" => "sub array",
"_id" => 172,
"_parent" => 163,
"_level" => 2,
),
'167' => array (
"desc" => "sub array from 172",
"_id" => 167,
"_parent" => 172,
"_level" => 3,
),
'200' => array (
"desc" => "sub array",
"_id" => 200,
"_parent" => 163,
"_level" => 2,
),
'165' => array (
"desc" => "sub array from 200",
"_id" => 165,
"_parent" => 200,
"_level" => 3,
),
);
如何才能获得此输出,我尝试使用usort并创建数组,但仍未获得我期望的输出。
答案 0 :(得分:0)
<?php
$myArray = array(
'163' => array (
"desc" => "master array",
"_id" => 163,
"_parent" => null,
"_level" => 1,
),
'172' => array (
"desc" => "sub array",
"_id" => 172,
"_parent" => 163,
"_level" => 2,
),
'167' => array (
"desc" => "sub array from 172",
"_id" => 167,
"_parent" => 172,
"_level" => 3,
),
'200' => array (
"desc" => "sub array",
"_id" => 200,
"_parent" => 163,
"_level" => 2,
),
'165' => array (
"desc" => "sub array from 200",
"_id" => 165,
"_parent" => 200,
"_level" => 3,
),
);
usort($myArray, function($a, $b) {
return ($a['_level'] <=> $b['_id']);
});
foreach($myArray as $array)
echo $array['desc']."<br>";
输出:
主阵列
子阵列
来自172的子阵列 子阵列
子阵列从200起