我得到了一个对象数组的数据库数据的结果
array(2) {
[0]=>
object(stdClass)#31 (1) {
["book_month"]=>
string(3) "Aug"
}
[1]=>
object(stdClass)#32 (1) {
["book_month"]=>
string(3) "Jun"
}
}但我需要一个月的结果作为一个排序顺序,如1月2月3月4月.....
我期望得到以下结果
array(2) {
[0]=>
object(stdClass)#31 (1) {
["book_month"]=>
string(3) "Jun"
}
[1]=>
object(stdClass)#32 (1) {
["book_month"]=>
string(3) "Aug"
}
}发布于 2013-07-12 21:44:32
uasort (reference)和usort (reference)允许您传递一个比较器函数,因此只需提供一个正确的比较器函数,按时间顺序对月份缩写进行排序。像这样的电话
uasort($your_array,'cmp');您必须编写一个正确的比较器函数,它将接收两个数组元素:
function cmp($a, $b) {
/*
* This function should return
* -1 if $a.bookmonth comes before $b.bookmonth
* 1 if $a.bookmonth comes after $b.bookmonth
* 0 if $a.bookmonth and $b.bookmonth are the same
*/
}创建这样一个函数的一种相当简单的方法是通过使用其他一些数组魔术将比较减少为对整数的测试:
$monthnames = array('Jan','Feb', 'Mar', 'Apr' ...)
...
$monthindex_a = array_search($a,$monthnames); // will return 0..11
// which are a lot easier to compare later on发布于 2013-07-12 22:07:15
为了扩展fvu的回答,下面是如何在php 5.3+中实现该解决方案
$monthnames = array('Jan','Feb', 'Mar', 'Apr', 'May','Jun','Jul','Aug','Sep', 'Oct', 'Nov','Dec');
usort($array, function($a, $b) use ($monthnames) {
return array_search($a->book_month, $monthnames) - array_search($b->book_month, $monthnames);
});https://stackoverflow.com/questions/17616322
复制相似问题