-2

I have a piece of a var_dump of one of my array items displayed here:

protected 'created_at' => 
object(Carbon\Carbon)[178]
public 'date' => string '2014-01-23 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Amsterdam' (length=16)

my question is how can I sort this array on the created_at variable? it should be descending.

Thanks for your effort!

Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
RvA
  • 43
  • 1
  • 1
  • 3
  • possible duplicate of [Reference: all basic ways to sort arrays and data in PHP](http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php) – deceze Mar 10 '14 at 11:29

1 Answers1

0

uasort() should do the trick!

See the working example here.

uasort($data, function($a, $b) {
  $first = $a['created_at']->format('U');
  $second= $b['created_at']->format('U');

  if ($first == $second) {
    return 0;
  }

  return ($first < $second) ? -1 : 1;
});

The callback is using the date's timestamp (->format('U');) to compare the two Dates. Please note, that uasort() maintains the key-value association while usort() does not.

Anticom
  • 975
  • 13
  • 29