1

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.

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.