ordered object array as per 3 letter month order i

2019-08-03 04:52发布

问题:

i got a result of database's data of an object array

array(2) {
  [0]=>
   object(stdClass)#31 (1) {
           ["book_month"]=>
                     string(3) "Aug"
       }
    [1]=>
               object(stdClass)#32 (1) {
               ["book_month"]=>
                  string(3) "Jun"
    }
}

but i need result as month as a sorting order like jan feb mar apr.....

I expect the following result

 array(2) {
  [0]=>
   object(stdClass)#31 (1) {
           ["book_month"]=>
                     string(3) "Jun"
       }
    [1]=>
               object(stdClass)#32 (1) {
               ["book_month"]=>
                  string(3) "Aug"
    }
}

回答1:

uasort (reference) and usort (reference) allow you to pass a comparator function, so just provide a proper comparator function that orders month abbreviations chronologically. For a call like this

uasort($your_array,'cmp');

You'll have to write a proper comparator function that will receive two array elements:

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
    */
}

A rather simple approach to create such a function would be to reduce the comparison to a test on integers by using some other array magic:

$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


回答2:

To expand on fvu's answer the following is how you would implement the solution in 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);
});