How can I convert array two dimensional to collection laravel?

懵懂的女人 提交于 2019-11-27 08:29:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!