我有一个数组,我想根据2值排序。
首先,我想根据c_gpa
值对其进行排序。如果c_gpa
值与数组中的其他值相等,则排序t_mark
值。
这是我的数组
$array = array(
[0]=>array(
"roll_number" => 1,
"c_gpa" => 4.8,
"t_mark"=>750
),
[1] => array(
"roll_number" => 2,
"c_gpa" => 4.12,
"t_mark"=>530
),
[2] => array(
"roll_number" => 3,
"c_gpa" => 4.12,
"t_mark"=>550
)
);
我在下面编写了排序c_gpa
值的代码但是有2个值是相同的(4.12)所以我想对它排序't_mark'值这些数组
usort($array, "all_filter");
function all_filter($a,$b) {
return $a['c_gpa'] < $b['c_gpa'];
}
我的预期输出是。
$array = array(
[0]=>array(
"roll_number" => 1,
"c_gpa" => 4.8,
"t_mark"=>750
),
[1] => array(
"roll_number" => 3,
"c_gpa" => 4.12,
"t_mark"=>550
),
[2] => array(
"roll_number" => 2,
"c_gpa" => 4.12,
"t_mark"=>530
)
);
提前致谢!!!
答案 0 :(得分:3)
您可以使用array_multisort函数执行此操作。
<?php
// Obtain a list of columns
foreach ($array as $key => $row) {
$c_gpa[$key] = $row['c_gpa'];
$t_mark[$key] = $row['t_mark'];
}
// Sort the data array with $c_gpa ASC, $t_mark ASC
// Add $data as the last parameter, to sort by the common key
array_multisort($c_gpa, SORT_DESC, $t_mark, SORT_ASC, $array);
var_dump($array);
?>
答案 1 :(得分:1)
如果您想使用usort()
,可以像这样使用它,demo
<?php
$array = array(
array(
"roll_number" => 1,
"c_gpa" => 4.8,
"t_mark"=>750
),
array(
"roll_number" => 2,
"c_gpa" => 4.12,
"t_mark"=>530
),
array(
"roll_number" => 3,
"c_gpa" => 4.12,
"t_mark"=>550
));
usort($array, function($a, $b){
return $a['c_gpa'] > $b['c_gpa'] ? true : $a['c_gpa'] < $b['c_gpa'] ? false : $a['t_mark'] < $b['t_mark'] ? true : false;
});
var_dump($array);