मेरे पास एक 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"},
-1
Miya 13 सितंबर 2018, 06:30

2 जवाब

सबसे बढ़िया उत्तर

इसको आजमाओ। आपको केवल 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
Romil 13 सितंबर 2018, 08:30

तुम यह केर सकते हो।

lodashjs का उपयोग करें! https://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);
0
seunggabi 13 सितंबर 2018, 06:43