首页 > 解决方案 > 在 Laravel 中使用集合进行过滤或可能的映射操作

问题描述

看起来我可能在这里有一个愚蠢的时刻。我有一个我试图根据几个条件过滤的集合。这是数组:

$files =[
   [
     "customisation_id" => "2357323",
     "file_type" => 2,
     "url" => "transparent/76caa009d0c2aa32793a8f48ad395dcb_616351.png.png"
  ],
  [
     "customisation_id" => "2357323",
     "file_type" => 3,
     "url" => "nonTransparent/5ae5a3ec64a35ebcaa26e211244c24a4_826308.jpg.png"
  ],
  [
     "customisation_id" => "2357324",
     "file_type" => 2,
     "url" => "transparent/5ae5a3ec64a35ebcaa26e211244c24a4_826308.jpg.gif"
  ],
  [
     "customisation_id" => "2357324",
     "file_type" => 3,
     "url" => "nonTransparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.png"
  ],
  [
      "customisation_id" => "2357350",
      "file_type" => 2,
      "url" => "transparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.gif"
  ],
  [
      "customisation_id" => "2357355",
      "file_type" => 3,
      "url" => "transparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.gif"
   ]
];

我想从中创建一个新数组,其中file_type of 2没有与相同的重复记录customisation_id。但是,如果没有重复记录,customer_id则只需将其添加到集合中。注意:我将数组与集合互换使用,因为我将为其使用集合。理想情况下,我想要一个具有以下结构的新数组或集合:

$files =[
   [
     "customisation_id" => "2357323",
     "file_type" => 2,
     "url" => "transparent/76caa009d0c2aa32793a8f48ad395dcb_616351.png.png"
  ],
  [
     "customisation_id" => "2357324",
     "file_type" => 2,
     "url" => "transparent/5ae5a3ec64a35ebcaa26e211244c24a4_826308.jpg.gif"
  ],
  [
      "customisation_id" => "2357350",
      "file_type" => 2,
      "url" => "transparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.gif"
  ],
  [
      "customisation_id" => "2357355",
      "file_type" => 3,
      "url" => "transparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.gif"
   ]
];

我已经尝试过 filter、map 和 reduce 收集方法,它们解决了难题的第一部分,但后来我陷入了第二个条件。
谢谢!

标签: phplaravel

解决方案


$newArray = collect($files)->unique('customisation_id')->values()->all();

您还应该阅读intersect()https ://laravel.com/docs/6.x/collections#method-intersect


推荐阅读