首页 > 解决方案 > Laravel 中的 Json 格式

问题描述

我有这个 JSON。

{
    "animals": [{
        "name": "Cumi-Cumi",
        "data": 1000
    }, {
        "name": "Udang",
        "data": 300
    }, {
        "name": "Baranang",
        "data": 12000
    }, {
        "name": "Cumi-Cumi",
        "data": 1500
    }, {
        "name": "Udang",
        "data": 500
    }, {
        "name": "Baranang",
        "data": 17000
    }, {
        "name": "Cumi-Cumi",
        "data": 2500
    }]
}

如何data按名称对密钥进行分组,如下所示:

{
    "animals": [{
            "name": "Cumi-Cumi",
            "data": [
                1000, 1500, 2500
            ]
        },
        {
            "name": "udang",
            "data": [
                300, 500
            ]
        },
        {
            "name": "Baranang",
            "data": [
                12000, 17000
            ]
        }
    ]
}

标签: laravel

解决方案


可能是因为我累了,但我不知道如何使这个更简洁......
无论如何这对你来说是一个开始。

$json = '{
    "animals": [{
        "name": "Cumi-Cumi",
        "data": 1000
    }, {
        "name": "Udang",
        "data": 300
    }, {
        "name": "Baranang",
        "data": 12000
    }, {
        "name": "Cumi-Cumi",
        "data": 1500
    }, {
        "name": "Udang",
        "data": 500
    }, {
        "name": "Baranang",
        "data": 17000
    }, {
        "name": "Cumi-Cumi",
        "data": 2500
    }]
}';

// Start by decoding the JSON (I assume it comes as a string, if not, then ignore this).
$collection = collect(json_decode($json, true))
// Now iterate over the keys (you only have one key (animals), but I wanted to be safe).
->map(function ($item) {
    // Convert the sub arrays into a Collection, then group the data against each animal name.
    // Then map (iterate) over each of the animals, one at a time.
    return collect($item)->groupBy('name')->map(function ($animal) {
        // Reduce each animal into a single entry.
        return $animal->reduce(function ($carry, $data) {
            // Use the name of the animal, then push the data onto the end. Feel free to sort at this point too!
            $carry['name'] = $data['name'];
            $carry['data'][] = $data['data'];
            return $carry;
        });
    // Finally, I reset the groupBy keys to ensure it matches your desired output.
    })->values();
});

推荐阅读