Laravel Collection从嵌套数据结构中获取唯一值 [英] Laravel Collection get unique values from nested datastructure

查看:52
本文介绍了Laravel Collection从嵌套数据结构中获取唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Laravel 5.1 Collection的Unique 方法从中过滤唯一ID嵌套的对象.

I want to use Laravel 5.1 Collection's Unique method to filter unique IDs from nested objects.

给出数据结构

{
  "key1": [
    {"id": 1},
    {"id": 1}
  ],
  "key2": [
    {"id": 1},
    {"id": 2}
  ]
}

我想返回从键1"中删除重复的 id 1 的相同数据结构.

I want to return the same datastructure with duplicate id 1 removed from "key 1".

我想使用 $ unique = $ collection-> unique('id'); ,但这似乎不适用于嵌套数据结构.

I wanted to use $unique = $collection->unique('id');, but this doesn't seem to apply to a nested datastructure as I have.

所以我想使用$ collection

So I thought to use $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.

结果结构应为:

{
  "key1": [
    {"id": 1}
  ],
  "key2": [
    {"id": 1},
    {"id": 2}
  ]
}

推荐答案

$collection = $collection->map(function ($array) {
    return collect($array)->unique('id')->all();
});

这篇关于Laravel Collection从嵌套数据结构中获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆