Manish
Manish

Reputation: 41

Get Unique Value from Nested Array- Laravel

I want to get the unique name with id from array in laravel. How can i get that? I've tried foreach loop like below but couldn't succeed.

$features=[];
    foreach ($vehicles as $key => $vehicle) {
        # code...
        $features[$key] = $vehicle->features;
    }
    
    $distinct_features = array_unique($features);

My array is like:

[[{"id":2,"name":"Airbags","image":"features\\January2021\\P69889cirEy57Asq9rld.png","active":1,"created_at":"2021-01-26T17:35:28.000000Z","updated_at":"2021-01-26T17:35:28.000000Z","pivot":{"vehicle_id":6,"feature_id":2}},{"id":3,"name":"ABS","image":"features\\January2021\\SpZJq3j30oISFqdYwxfU.png","active":0,"created_at":"2021-01-26T17:36:00.000000Z","updated_at":"2021-02-22T10:33:26.000000Z","pivot":{"vehicle_id":6,"feature_id":3}}],[{"id":2,"name":"Airbags","image":"features\\January2021\\P69889cirEy57Asq9rld.png","active":1,"created_at":"2021-01-26T17:35:28.000000Z","updated_at":"2021-01-26T17:35:28.000000Z","pivot":{"vehicle_id":7,"feature_id":2}}],[{"id":2,"name":"Airbags","image":"features\\January2021\\P69889cirEy57Asq9rld.png","active":1,"created_at":"2021-01-26T17:35:28.000000Z","updated_at":"2021-01-26T17:35:28.000000Z","pivot":{"vehicle_id":8,"feature_id":2}}],[{"id":2,"name":"Airbags","image":"features\\January2021\\P69889cirEy57Asq9rld.png","active":1,"created_at":"2021-01-26T17:35:28.000000Z","updated_at":"2021-01-26T17:35:28.000000Z","pivot":{"vehicle_id":9,"feature_id":2}},{"id":3,"name":"ABS","image":"features\\January2021\\SpZJq3j30oISFqdYwxfU.png","active":0,"created_at":"2021-01-26T17:36:00.000000Z","updated_at":"2021-02-22T10:33:26.000000Z","pivot":{"vehicle_id":9,"feature_id":3}}],[{"id":2,"name":"Airbags","image":"features\\January2021\\P69889cirEy57Asq9rld.png","active":1,"created_at":"2021-01-26T17:35:28.000000Z","updated_at":"2021-01-26T17:35:28.000000Z","pivot":{"vehicle_id":10,"feature_id":2}},{"id":3,"name":"ABS","image":"features\\January2021\\SpZJq3j30oISFqdYwxfU.png","active":0,"created_at":"2021-01-26T17:36:00.000000Z","updated_at":"2021-02-22T10:33:26.000000Z","pivot":{"vehicle_id":10,"feature_id":3}}]]

Thanks in advance.

Upvotes: 1

Views: 1477

Answers (1)

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

You can use unique() method of laravel collection

collect($vehicles)
    ->flatten(1)
    ->unique(function ($item) {
        return $item['id'] . $item['name'];
    });

As you have your data in different arrays, I've flatten it to one level to have all of them in one array, then I've defined a closure function to define your custom uniqueness logic(combination of id and name).

Upvotes: 1

Related Questions