This question already has an answer here:
这个问题在这里已有答案:
- How can I sort arrays and data in PHP? 9 answers
如何在PHP中对数组和数据进行排序? 9个答案
Given this array:
给定这个数组:
Array
(
[0] => Array
(
[status] => closed
[userModifiedAt] => 2015-12-09T11:47:46Z
)
[1] => Array
(
[status] => active
[userModifiedAt] => 2016-02-08T16:43:26Z
)
[2] => Array
(
[status] => closed
[userModifiedAt] => 2016-03-31T03:47:19Z
)
[3] => Array
(
[status] => pending
[userModifiedAt] => 2015-12-08T14:09:58Z
)
I'd like to order it by [status] with this order: - pending - active - closed
我想通过[status]订购此订单: - 待处理 - 活动 - 已关闭
And for each status, order by [userModifiedAt].
对于每个状态,按[userModifiedAt]排序。
I'm using this code:
我正在使用此代码:
usort($array, function($a,$b){ return strcmp($a['status'], $b['status']);} );
But it works alphabetically, so the status is ordered as: - active - closed - pending
但它按字母顺序排列,因此状态按以下顺序排序: - 活动 - 关闭 - 待定
How can I order an array according to a predefined order list?
如何根据预定义的订单列表订购数组?
1 个解决方案
#1
7
This would be a trick -
这将是一个伎俩 -
## A array with the orders to be considered
$order = array('active' => 1, 'closed' => 2, 'pending' => 3);
usort($array, function($a, $b) use($order) { // Use the order array to compare
return $order[$a[status]] - $order[$b[status]];
});
var_dump($array);
Output
array(4) {
[0]=>
array(2) {
["status"]=>
string(6) "active"
["userModifiedAt"]=>
string(20) "2016-02-08T16:43:26Z"
}
[1]=>
array(2) {
["status"]=>
string(6) "closed"
["userModifiedAt"]=>
string(20) "2015-12-09T11:47:46Z"
}
[2]=>
array(2) {
["status"]=>
string(6) "closed"
["userModifiedAt"]=>
string(20) "2016-03-31T03:47:19Z"
}
[3]=>
array(2) {
["status"]=>
string(7) "pending"
["userModifiedAt"]=>
string(20) "2015-12-08T14:09:58Z"
}
}
Change the order array
if you want different order. Key with lowest value will be first on the array
. If you want closed to be first then provide the lowest value to it in $order
array.
如果您想要不同的订单,请更改订单数组。具有最低值的键将首先在阵列上。如果你想先关闭,那么在$ order数组中为它提供最低值。
#1
7
This would be a trick -
这将是一个伎俩 -
## A array with the orders to be considered
$order = array('active' => 1, 'closed' => 2, 'pending' => 3);
usort($array, function($a, $b) use($order) { // Use the order array to compare
return $order[$a[status]] - $order[$b[status]];
});
var_dump($array);
Output
array(4) {
[0]=>
array(2) {
["status"]=>
string(6) "active"
["userModifiedAt"]=>
string(20) "2016-02-08T16:43:26Z"
}
[1]=>
array(2) {
["status"]=>
string(6) "closed"
["userModifiedAt"]=>
string(20) "2015-12-09T11:47:46Z"
}
[2]=>
array(2) {
["status"]=>
string(6) "closed"
["userModifiedAt"]=>
string(20) "2016-03-31T03:47:19Z"
}
[3]=>
array(2) {
["status"]=>
string(7) "pending"
["userModifiedAt"]=>
string(20) "2015-12-08T14:09:58Z"
}
}
Change the order array
if you want different order. Key with lowest value will be first on the array
. If you want closed to be first then provide the lowest value to it in $order
array.
如果您想要不同的订单,请更改订单数组。具有最低值的键将首先在阵列上。如果你想先关闭,那么在$ order数组中为它提供最低值。