Gro*_*ler 1 php collections filter laravel laravel-5.1
我想使用Laravel 5.1 Collection的Unique方法从嵌套对象中过滤唯一ID.
鉴于数据结构
{
"key1": [
{"id": 1},
{"id": 1}
],
"key2": [
{"id": 1},
{"id": 2}
]
}
Run Code Online (Sandbox Code Playgroud)
我想返回相同的数据结构,重复id 1从"键1"中删除.
我想使用$unique = $collection->unique('id');,但这似乎不适用于我所拥有的嵌套数据结构.
所以我想用$ 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');
Run Code Online (Sandbox Code Playgroud)
我不太清楚如何构建它.
结果结构应该是:
{
"key1": [
{"id": 1}
],
"key2": [
{"id": 1},
{"id": 2}
]
}
Run Code Online (Sandbox Code Playgroud)
Ali*_*deh 10
如果您的数据结构嵌套在单层中,无论是数组还是对象,都很简单
$unique = $collection->unique('key')
Run Code Online (Sandbox Code Playgroud)
完成工作。
$collection = $collection->map(function ($array) {
return collect($array)->unique('id')->all();
});
Run Code Online (Sandbox Code Playgroud)