Q:

php- error sorting array with time stamps as values

This might be a simple one but i have been struggling to get the output sorted correctly for an array.  
I want to sort the following array by the date time values in ascending order. 
Array ( 
[2] => 
[5] => DateTime Object ( [date] => 2015-10-08 08:30:00.000000 [timezone_type] => 3 [timezone] => Asia/Kolkata ) 
[6] => DateTime Object ( [date] => 2015-12-01 01:00:00.000000 [timezone_type] => 3 [timezone] => Asia/Kolkata ) 
[4] => DateTime Object ( [date] => 2015-12-31 11:30:00.000000 [timezone_type] => 3 [timezone] => Asia/Kolkata ) 
[3] => DateTime Object ( [date] => 2015-12-04 13:00:00.000000 [timezone_type] => 3 [timezone] => Asia/Kolkata ) 
[1] => DateTime Object ( [date] => 2015-12-30 07:00:00.000000 [timezone_type] => 3 [timezone] => Asia/Kolkata ) 
[0] => DateTime Object ( [date] => 2015-12-01 02:00:00.000000 [timezone_type] => 3 [timezone] => Asia/Kolkata ) 
 ) 

I have tried uasort as below but it did not provide the correct sorting.  Did anyone faced this issue earlier? 
uasort($item_date_converted, function ($a, $b) { return $a - $b; });

A:

DateTime objects can be compared using standard comparison operators.  So if you want to use uasort, you just need to alter your comparison function so that it returns the expected value.  The PHP documentation of uasort refers you to the documentation of usort for explanation of user-defined comparison functions, which says:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.  

So your uasort can be done like this:
uasort($item_date_converted, function ($a, $b) {
    if ($a < $b) return -1;
    if ($a > $b) return 1;
    return 0;        
});

This can be further simplified by using asort rather than uasort.  If this is just an array of DateTime objects, it can be sorted without a user function.  It is this simple:
asort($item_date_converted);

