[英]How to sort multidimensional array with respect to the first value of nested array in php?
I would like to sort a multidimensional array with respect to the first value of a nested array.我想根据嵌套数组的第一个值对多维数组进行排序。 For the example below the result should be [[1,3],[3, 6],[10, 20], [16, 19]].对于下面的示例,结果应该是 [[1,3],[3, 6],[10, 20], [16, 19]]。 I tried this but nothing happened.我试过这个,但什么也没发生。 I would like to know where I am making a mistake using usort().我想知道我在哪里使用 usort() 犯了错误。
function cmp($x, $y){
global $arrint;
if ($x[0] == $y[0]) {
return 0;
}
return ($x[0] < $y[0]) ? -1 : 1;
}
$arrint = [
[10, 20],
[16, 19],
[3, 6],
[1,3]
];
usort($arrint, "cmp");
You can make your sorting logic less verbose by using the spaceship operator ( <=>
).您可以使用飞船运算符 ( <=>
) 使排序逻辑不那么冗长。
$arrint = [
[10, 20],
[16, 19],
[3, 6],
[1,3]
];
usort($arrint, function ($a, $b) {
return $a[0] <=> $b[0];
});
var_dump($arrint);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.