Juliver Galleto
Juliver Galleto

Reputation: 9037

Sort array based on its object's value which contains a timestamp

First I create 2 different queries.

$first = first::where('id',$request->first_id)->select('name','created_at')->get();
$second = second::where('id', $request->second_id)->select('name','created_at')->get();

I then merge the two resulting arrays.

$data_combine = array_merge($first->toArray(), $second->toArray());

Finally, I'd like to sort the combined arrays in ascending order based on their created_at value, e.g '2016-05-06 16:43:46'.

Upvotes: 1

Views: 728

Answers (3)

Andrii Lutskevych
Andrii Lutskevych

Reputation: 1379

No need to use toArray(), because Collection have all() method:

$combine = collect(array_merge($first->all(), $second->all()))->sortByDesc("created_at");

If you have only one element in the both arrays, can try:

$combine = collect([$first->first(), $second->first()])->sortByDesc("created_at");

Upvotes: 0

Matt McDonald
Matt McDonald

Reputation: 5050

You can do this easily with Laravel Collection methods. Unlike a regular array, with a Collection you'll still have access to all the other helpful collection methods Laravel makes available on Models.

You can merge your arrays into a new collection and then sort that collection.

collect(array_merge($first -> toArray(), $second -> toArray())) -> sortBy('created_at');

A more fluent way of writing the above would also work

$first -> push($second) -> flatten() -> sortBy('created_at');

For this to work created_at needs to be visible. If not already defined as such in your Model's visible property (and safe to do so) you'd need to add that first. Otherwise, you'd need to loop the initial collections and run addVisible('created_at') to make it visible for your current result.

Upvotes: 3

Ankit
Ankit

Reputation: 1887

$array = array_values(array_sort($data_combine , function ($value) {
    return $value['created_at'];
}));

You can sort your merged array using array_sort function.

https://laravel.com/docs/5.0/helpers#arrays

Upvotes: 1

Related Questions