Search code examples
phparrayslaravellaravel-5laravel-collection

Laravel - How to sort array objects by timestamp value of different keys?


I have this array of objects from a Laravel merged collection, accessed like this, $collection->values()->all(), which returns the following:

 [
  {
    "id": "1",
    "type": "Teacher",
    "created_at": "2017-05-11 18:00:00"
  },
  {
    "id": "2",
    "type": "Student"
    "created_at": "2017-05-11 15:00:00"
  },
  {
    "id": "3",
    "type": "Course",
    "data": {
       "title: "PHP",
       "created_at": "2017-05-11 16:00:00"
    }
  }
]

I am trying to sort the order by the created_at field, so it looks like this:

 [
  {
    "id": "1",
    "type": "Teacher",
    "created_at": "2017-05-11 18:00:00"
  },
  {
    "id": "3",
    "type": "Course",
    "data": {
       "title: "PHP",
       "created_at": "2017-05-11 16:00:00"
    }
  },
  {
    "id": "2",
    "type": "Student"
    "created_at": "2017-05-11 15:00:00"
  }
]

The issue is that created_at is in two locations, sometimes it's under created_at and other times it's under data.created_at.


Solution

  • I think you can use the sortByDescfunction:

    $sorted = $collection->sortByDesc(function ($element) {
        return $element->data ? $element->data->created_at : $element->created_at;
    });