如何按值对多维数组进行排序? [英] How to Sort Multi-dimensional Array by Value?
问题描述
如何通过"order"键的值对该数组排序?即使这些值当前是连续的,也不一定总是如此.
How can I sort this array by the value of the "order" key? Even though the values are currently sequential, they will not always be.
Array
(
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
)
推荐答案
尝试 usort ,如果您仍使用PHP 5.2或更早版本,则必须首先定义排序功能:
Try a usort, If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
从PHP 5.3开始,您可以使用匿名函数:
Starting in PHP 5.3, you can use an anonymous function:
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
最后,在PHP 7中,您可以使用太空飞船运算符:
And finally with PHP 7 you can use the spaceship operator:
usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
要将其扩展到多维排序,如果第二个/第三个排序元素为零,请参考第二个/第三个排序元素-下文将详细说明.您还可以使用它对子元素进行排序.
To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.
usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
如果需要保留键关联,请使用uasort()
-请参见比较数组排序功能在手册中
If you need to retain key associations, use uasort()
- see comparison of array sorting functions in the manual
这篇关于如何按值对多维数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!