1

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'.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

does not sort in seconds difference. Any ideas?
Good point @Ankit - they need to be arrays merged into a collection instead. Correcting the logic as above should now sort correctly.
1
$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

1 Comment

does this work in Laravel 5.0? I'm not on 5.1 yet sadly.
0

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");

Comments

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.