【问题标题】:How can I convert array two dimensional to collection laravel?如何将二维数组转换为集合 laravel?
【发布时间】:2018-12-31 11:39:45
【问题描述】:

我有这样的数组:

$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


【解决方案1】:

collect($test) 不会将$test 转换为集合,而是将$test 作为集合返回。您需要将其返回值用于新变量,或覆盖现有变量。

$test = collect($test);

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

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

【讨论】:

  • 如果我dd{$test) 的结果是这样的:postimg.cc/image/ro3mko4d9。它是一个数组。我想要这样的结果:postimg.cc/image/fyzmwq0jx。所以我希望它成为一个对象。不是数组
  • 您说的是单个数组项?如果您希望它们成为对象,那么您需要将它们转换为对象。我已经更新了答案,以展示您如何做到这一点。
  • 也许你可以再次帮助我。看看这个:stackoverflow.com/questions/51487769/…。我想使用chunk 更改它。但我仍然对实现它感到困惑
【解决方案2】:

分享更多的光。

集合是“可宏化的”,它允许您在运行时向 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.


【讨论】:

    【解决方案3】:

    我知道已经有一段时间了,但我在 laracast 上找到了这个答案,它似乎更好地解决了这个问题,因为它使它成为递归的。 这个解决方案是我从https://gist.github.com/brunogaspar/154fb2f99a7f83003ef35fd4b5655935 github 得到的,效果很好。

    \Illuminate\Support\Collection::macro('recursive', function () {
    return $this->map(function ($value) {
        if (is_array($value) || is_object($value)) {
            return collect($value)->recursive();
        }
    
        return $value;
    });
    

    });

    比你喜欢的:

    $data = [
    [
        'name' => 'John Doe',
        'emails' => [
            'john@doe.com',
            'john.doe@example.com',
        ],
        'contacts' => [
            [
                'name' => 'Richard Tea',
                'emails' => [
                    'richard.tea@example.com',
                ],
            ],
            [
                'name' => 'Fergus Douchebag', // Ya, this was randomly generated for me :)
                'emails' => [
                    'fergus@douchebag.com',
                ],
            ],
        ],
      ],
    ];
    $collection = collect($data)->recursive();
    

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2018-02-26
      • 2016-05-12
      • 2011-07-05
      • 2019-07-09
      • 2015-07-16
      相关资源
      最近更新 更多