php - 在 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 收集方法,它们解决了难题的第一部分,但后来我陷入了第二个条件。
谢谢!
解决方案
$newArray = collect($files)->unique('customisation_id')->values()->all();
您还应该阅读intersect()
:https ://laravel.com/docs/6.x/collections#method-intersect
推荐阅读
- scikit-learn - 线性回归中的截距
- java - 如何重构此 Java 代码使其更干燥?
- julia - Julia:我们如何计算伴随或经典伴随(线性代数)?
- reactjs - 反应钩子无法在未安装的组件中执行设置状态
- java - 是否可以在项目中只有 1 个 IAnnotationTransformer 实现
- c++ - 这种基于线程 ID 的同步是否安全且整洁?
- javascript - 如何检查javascript中的第一个字母是否为大写
- mysql - 运行 mySQL 语句不会返回任何内容
- github - 为什么当我在 GitHub 的 GraphQL API 中两次调用同一字段(使用不同的查询)时能够绕过分页
- typescript - 如何使用 Selenium WebDriver 与 createSession() 同步启动 Chrome?