如何按值对多维数组进行排序 [英] How to Sort a 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屋!