如何将json数组更改为另一种格式

时间:2018-09-13 03:30:23

标签: jquery arrays json

我有一个JSON数组,我需要将其更改为另一种数组格式。请查看以下数组,

我的数组是

Array{
BUS NO.1:
Array{
0:{trip: "Trip00011", runningKm: "5000"}
1:{trip: "Trip00012", runningKm: "2565"}},

BUS NO.2:
Array{
0:{trip: "Trip00021", runningKm: "2400"}
1:{trip: "Trip00023", runningKm: "1500"}
2:{trip: "Trip00025", runningKm: "3000"}}

}

我需要

data :[{y:BUS NO.1, "Trip00011": "5000","Trip00012":"2565"},
    {y:BUS NO.2, "Trip00021": "2400","Trip00023":"1500","Trip00025":"3000"},

2 个答案:

答案 0 :(得分:1)

尝试这个。您只需要1个循环和一个array_merge。

$originalData = [
    [
        'vehicle' => 'BUS NO.1',
        'trip_name' => 'Trip00011', 
        'running_km' => '5000'
    ],
    [
        'vehicle' => 'BUS NO.2',
        'trip_name' => 'Trip00021', 
        'running_km' => '2400'
    ],
    [
        'vehicle' => 'BUS NO.2',
        'trip_name' => 'Trip00023', 
        'running_km' => '1500'
    ],
];

$responseData = [];

foreach ($originalData as $od){
    $temp = [
        'y' => $od['vehicle'],
    ];

    $temp[$od['trip_name']] = $od['running_km'];

    if (!isset($responseData[$od['vehicle']])){
        $responseData[$od['vehicle']] = $temp;  
    } else {
        $responseData[$od['vehicle']] = array_merge($responseData[$od['vehicle']], $temp);
    }
}

echo json_encode(array_values($responseData));

输出(JSON):[{"y":"BUS NO.1","Trip00011":"5000"},{"y":"BUS NO.2","Trip00021":"2400","Trip00023":"1500"}]

答案 1 :(得分:0)

您可以这样做。

使用lodashjshttps://lodash.com/docs/4.17.10#forEach

const busData = {
    bus1:[
        {trip: "Trip00011", runningKm: "5000"},
        {trip: "Trip00012", runningKm: "2565"}
    ],
    bus2:[
        {trip: "Trip00021", runningKm: "2400"},
        {trip: "Trip00023", runningKm: "1500"},
        {trip: "Trip00025", runningKm: "3000"}
    ]
}

const busInfoAll = []
_.forEach(busData, (busList, busNo) => {
    const busInfo = {y: busNo};
    busList.forEach((bus) => {
        busInfo[bus.trip] = bus.runningKm;
    });
    busInfoAll.push(busInfo);
});

console.log(busInfoAll);