【问题标题】:Get Unique Value from Nested Array- Laravel从嵌套数组中获取唯一值 - Laravel
【发布时间】:2021-05-31 16:06:00
【问题描述】:

我想从 laravel 的数组中获取带有 id 的唯一名称。我怎么能得到那个?我尝试了如下的 foreach 循环,但没有成功。

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

我的数组是这样的:

[[{"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}}]]

提前致谢。

【问题讨论】:

标签: arrays laravel foreach


【解决方案1】:

你可以使用laravel collectionunique()方法

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

由于您将数据放在不同的数组中,因此我将其扁平化到一个级别以将它们全部放在一个数组中,然后我定义了一个闭包函数来定义您的自定义唯一性逻辑(id 的组合 名称)。

【讨论】:

    猜你喜欢
    • 2016-02-07
    • 1970-01-01
    • 2020-11-06
    • 2016-06-06
    • 2015-04-26
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多