Laravel Collection 从嵌套数据结构中获取唯一值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33571628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Collection get unique values from nested datastructure
提问by Growler
I want to use Laravel 5.1 Collection's Uniquemethod to filter unique IDs from nested objects.
我想使用Laravel 5.1 Collection 的 Unique方法来过滤嵌套对象中的唯一 ID。
Given the data structure
给定数据结构
{
"key1": [
{"id": 1},
{"id": 1}
],
"key2": [
{"id": 1},
{"id": 2}
]
}
I want to return the same datastructure with duplicate id 1
removed from "key 1".
我想返回id 1
从“key 1”中删除重复项的相同数据结构。
I wanted to use $unique = $collection->unique('id');
, but this doesn't seem to apply to a nested datastructure as I have.
我想使用$unique = $collection->unique('id');
,但这似乎不适用于我拥有的嵌套数据结构。
So I thought to use $collection
所以我想用 $collection
$input = $request->all();
$collection = collect($input);
$collection->each(function($obj, $key) {
//$key is "key1", "key2"
//obj is the associated array of objects containing IDs
})->unique('id');
I don't quite know how to structure this.
我不太知道如何构建它。
The result structure should be:
结果结构应该是:
{
"key1": [
{"id": 1}
],
"key2": [
{"id": 1},
{"id": 2}
]
}
回答by Joseph Silber
$collection = $collection->map(function ($array) {
return collect($array)->unique('id')->all();
});
回答by pankaj kumar
if you have numeric List then you can use this code
如果您有数字列表,则可以使用此代码
$dataList = [1,2,4,5,3,2,1,98,1,2,4,5,6];
$dataList = collect( $dataList )->unique();
you will get all the unique list.
您将获得所有唯一列表。
[1,2,4,5,3,98,6]