0

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.

2
  • And what is the problem? Commented May 18, 2017 at 19:35
  • @mimo's answer does exactly what you need Commented May 18, 2017 at 19:44

1 Answer 1

4

I think you can use the sortByDescfunction:

$sorted = $collection->sortByDesc(function ($element) {
    return $element->data ? $element->data->created_at : $element->created_at;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Switch to sortByDesc since the author wants to sort the date in descending order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.