I have array like this :
$test = array(
array(
'name' => 'Christina',
'age' => '25'
),
array(
'name' => 'Agis',
'age' => '22'
),
array(
'name' => 'Agnes',
'age' => '30'
)
);
I want to change it to collection laravel
I try like this :
collect($test)
The results are not perfect. There is still an array
How can I solve this problem?
collect($test)
does not convert $test
to a collection, it returns $test
as a collection. You need to use it's return value for a new variable, or override the existing one.
$test = collect($test);
If you want to convert the individual items to objects (instead of arrays) like you indicated in the comment below, then you will need to cast them.
$test = collect($test)->map(function ($item) {
return (object) $item;
});
I know it's been a while, but i found this answer on laracast and it seems to solve the issue better, cause it make it recursive. This solution I've got from https://gist.github.com/brunogaspar/154fb2f99a7f83003ef35fd4b5655935 github and works like a charm.
\Illuminate\Support\Collection::macro('recursive', function () {
return $this->map(function ($value) {
if (is_array($value) || is_object($value)) {
return collect($value)->recursive();
}
return $value;
});
});
than you go like:
$data = [
[
'name' => 'John Doe',
'emails' => [
'[email protected]',
'[email protected]',
],
'contacts' => [
[
'name' => 'Richard Tea',
'emails' => [
'[email protected]',
],
],
[
'name' => 'Fergus Douchebag', // Ya, this was randomly generated for me :)
'emails' => [
'[email protected]',
],
],
],
],
];
$collection = collect($data)->recursive();
To share more light.
Collections are "macroable", which allows you to add additional methods to the Collection class at run time. According to Laravel explanation on collections. Arrays can be dimensional. using the map function extends your collection to convert child array into objects
$test = array(
array(
'name' => 'Christina',
'age' => '25'
),
array(
'name' => 'Agis',
'age' => '22'
),
array(
'name' => 'Agnes',
'age' => '30'
)
);
// can be converted using collection + map function
$test = collect($test)->map(function($inner_child){
return (Object) $inner_child;
});
This will cast the inner child array into Object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With