Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array From Laravel Collection

Im using Laravel 4.2. This maybe quite simple. When i get result from eloquent model using ->get(), i get this type of result

[{"name":"JOHN","tel":"12345"},{"name":"JANE","tel":"67890"}]

And I want to convert to this format

[["JOHN","12345"],["JANE","67890"]]

I've been struggling with this issue and I don't know what exact keyword to search for.

like image 330
luca ditrimma Avatar asked Sep 09 '26 04:09

luca ditrimma


2 Answers

Use the map() collection method and array_values(). Just tested this and it's working perfectly:

$collection->map(function ($i) {
    return array_values($i);
})->toArray();

In 4.2 use array_map:

array_map(function ($i) {
    return array_values($i);
}, $collection->toArray());
like image 122
Alexey Mezenin Avatar answered Sep 10 '26 18:09

Alexey Mezenin


https://laravel.com/docs/4.2/eloquent#collections

This may be a shorter way to do as each method is availble on collections too, Although @Alexey Answer is nice one.

$collection->each(function ($i) {
    return array_values($i);
})->toArray();
like image 41
Abhishek Avatar answered Sep 10 '26 19:09

Abhishek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!