Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Collection get unique values from nested datastructure

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

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".

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

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.

The result structure should be:

{
  "key1": [
    {"id": 1}
  ],
  "key2": [
    {"id": 1},
    {"id": 2}
  ]
}
like image 437
user3871 Avatar asked Nov 06 '15 16:11

user3871


3 Answers

$collection = $collection->map(function ($array) {
    return collect($array)->unique('id')->all();
});
like image 71
Joseph Silber Avatar answered Oct 21 '22 13:10

Joseph Silber


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]
like image 31
pankaj kumar Avatar answered Oct 21 '22 12:10

pankaj kumar


If your data structure is nested a single level, be it arrays or objects, simple

$unique = $collection->unique('key')

does the job.

like image 3
Ali Bakhshandeh Avatar answered Oct 21 '22 14:10

Ali Bakhshandeh