How can I convert array two dimensional to collection laravel?

限于喜欢 提交于 2019-11-28 14:22:57

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

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.


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