问题
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?
回答1:
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;
});
回答2:
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.
来源:https://stackoverflow.com/questions/51488623/how-can-i-convert-array-two-dimensional-to-collection-laravel