[英]php array sort numeric first and alphabetic last
I have an array: 我有一个数组:
Array
(
...
[14] => Array
(
[date] => 2014-04-14
[period] => 6
)
[15] => Array
(
[date] => 2014-04-21
[period] => R1
)
[16] => Array
(
[date] => 2014-04-21
[period] => R2
)
[17] => Array
(
[date] => 2014-04-21
[period] => 4
)
[18] => Array
(
[date] => 2014-04-21
[period] => 8
)
[19] => Array
(
[date] => 2014-04-28
[period] => 1
)
...
)
It has 2 types of sorts: Date and Period. 它有2种类型:日期和期间。 But in the same time, the sort of the Period item is numeric and alphabetic. 但同时,“期间”项目的类型是数字和字母。 Looking the example of day 2014-04-21 : 以2014年4月21日为例:
[15] => Array
(
[date] => 2014-04-21
[period] => R1
)
[16] => Array
(
[date] => 2014-04-21
[period] => R2
)
[17] => Array
(
[date] => 2014-04-21
[period] => 4
)
[18] => Array
(
[date] => 2014-04-21
[period] => 8
)
Is it possible to sort numerically and later alphabetically? 是否可以按数字排序,然后按字母顺序排序? I need a similar result: 我需要类似的结果:
[15] => Array
(
[date] => 2014-04-21
[period] => 4
)
[16] => Array
(
[date] => 2014-04-21
[period] => 8
)
[17] => Array
(
[date] => 2014-04-21
[period] => R1
)
[18] => Array
(
[date] => 2014-04-21
[period] => R2
)
I use this code: 我使用以下代码:
function cmp($a, $b) {
if ($a['date'] == $b['date']) {
if(is_numeric($a['period']) && !is_numeric($b['period'])) {
return 1;
}
else if(!is_numeric($a['period']) && is_numeric($b['period'])) {
return -1;
}
else {
return ($a['period'] < $b['period']) ? -1 : 1;
}
}
return (strtotime($a['date']) < strtotime($b['date']))? -1 : 1;
}
usort($arr, "cmp");
you should change direction in first two conditions: 您应该在前两个条件下更改方向:
if(is_numeric($a['period']) && !is_numeric($b['period'])) {
return -1;
}
else if(!is_numeric($a['period']) && is_numeric($b['period'])) {
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.