如何在PHP中使用条件对数组进行排序? 我希望按ID排序的数组然后按ID中的父ID 排序,而不是在ID 之后。 这样做的原因是将其实现为jQuery TreeGrid。
例如:
func
排序后,变成这样:
Array
(
[0] => Array
(
[0] => 1 //ID
[1] => TEST //Name
[2] => 1 //Parent ID
)
[1] => Array
(
[0] => 2 //ID
[1] => TEST //Name
[2] => 2 //Parent ID
)
[2] => Array
(
[0] => 3 //ID
[1] => TEST //Name
[2] => 3 //Parent ID
)
[3] => Array
(
[0] => 4 //ID
[1] => TEST //Name
[2] => 1 //Parent ID
)
[4] => Array
(
[0] => 5 //ID
[1] => TEST //Name
[2] => 2 //Parent ID
)
)
答案 0 :(得分:0)
您可以使用array_multisort ()。
//get lists to sort by
foreach ($your_array as $key => $value) {
$id_array[$key] = $value[0];
$parent_id_array[$key] = $value[2];
}
//sort first by `id` ascending, then by `parent_id` ascending
array_multisort ($id_array, SORT_ASC, $parent_id_array, SORT_ASC, $your_array);
您甚至可以使用array_orderby ()
:
$your_array = array_orderby ($your_array, 0, SORT_ASC, 2, SORT_ASC);
答案 1 :(得分:0)
使用此代码。它会起作用
foreach ($data as $key => $row) {
$id[$key] = $row[0];
$parent_id[$key] = $row[2];
}
array_multisort($id,SORT_ASC,$parent_id,SORT_ASC,$data);