【问题标题】:Merge Laravel Collection Items into new array将 Laravel 集合项合并到新数组中
【发布时间】:2018-07-22 10:14:12
【问题描述】:

我想合并这个集合项目:

Collection {#1242 ▼
 #items: array:2 [▼
   0 => "1,2,3"
   1 => "4,5,6"
  ]
}

进入这个新数组:

array:6 [▼
  0 => "1"
  1 => "2"
  2 => "3"
  3 => "4"
  4 => "5"
  5 => "6"
]

有没有简单的方法来合并和重新排列? 谢谢。

【问题讨论】:

标签: php arrays collections laravel-5.3


【解决方案1】:

您可以使用Laravel Collection 方法调用map,然后只使用explode 里面的每个项目和flatten 结果,也可以使用all 返回一个数组,如下所示:

$collection = $collection->map(function ($item) {
     return explode(',', $item);
})->flatten()->all();

【讨论】:

  • 完美运行。帮助我在编辑表单加载后自动勾选/取消勾选复选框列表。布拉沃尼古拉·加夫里克 !!!..
【解决方案2】:

我希望这可以用于你的情况

/*
$collection=[
   0 => "1,2,3"
   1 => "4,5,6"
];
* if the above is your collection
*/

$result=[];

$collection->each(function($item)use($result){
    array_push($result, explode(',', $item));
});

dd($result)

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 2017-03-07
    • 2022-09-23
    • 2016-05-19
    • 2018-09-23
    • 2018-11-11
    • 2017-07-08
    • 2018-07-17
    • 1970-01-01
    相关资源
    最近更新 更多