如何将数组二维转换为集合laravel?

问题描述 投票:1回答:2

我有这样的数组:

$test = array(
    array(
        'name' => 'Christina',  
        'age' => '25' 
    ),
    array(
        'name' => 'Agis', 
        'age' => '22'
    ),
    array(
        'name' => 'Agnes', 
        'age' => '30'
    )
);

我想把它改成收藏laravel

我试着这样:

collect($test)

结果并不完美。还有一个阵列

我怎么解决这个问题?

arrays laravel collections laravel-5.6
2个回答
2
投票

collect($test)没有将$test转换为集合,它将$test作为集合返回。您需要将它的返回值用于新变量,或覆盖现有变量。

$test = collect($test);

如果您想将各个项目转换为对象(而不是数组),就像您在下面的注释中指出的那样,那么您将需要转换它们。

$test = collect($test)->map(function ($item) {
    return (object) $item;
});

0
投票

分享更多光。

集合是“可宏”的,它允许您在运行时向Collection类添加其他方法。根据Laravel对收藏品的解释。数组可以是维度的。使用map函数扩展您的集合以将子数组转换为对象

$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.


© www.soinside.com 2019 - 2024. All rights reserved.