2017-04-23 24 views
0

我試圖獲得關於電影日程安排的API。但是json的輸出並不是我想要的。我想按劇院排序,而不是按電影排序。所以,我應該改變json值的位置,這可能嗎?該輸出JSON我從API來自API更改位置的PHP JSON

{ 
    "data": [ 
     { 
      "movie": "movie A", 
      "schedule": [ 
       { 
        "theater": "theater A", 
        "time": [ 
         "13:00", 
         "15:00", 
         "17:00", 
         "19:00", 
         "21:00" 
        ], 
        "price": "Rp.60,000" 
       }, 
       { 
        "theater": "theater B", 
        "time": [ 
         "13:00", 
         "15:00", 
         "17:00", 
         "19:00", 
         "21:00" 
        ], 
        "price": "Rp.50,000" 
       } 
      ] 
     } 
     { 
      "movie": "movie B", 
      "schedule": [ 
       { 
        "theater": "theater A", 
        "time": [ 
         "13:00", 
         "15:00", 
         "17:00", 
         "19:00", 
         "21:00" 
        ], 
        "price": "Rp.60,000" 
       }, 
       { 
        "theater": "theater B", 
        "time": [ 
         "13:00", 
         "15:00", 
         "17:00", 
         "19:00", 
         "21:00" 
        ], 
        "price": "Rp.50,000" 
       } 
      ] 
     } 
    ] 
} 

在這裏,我想什麼JSON有

{ 
    "data": [ 
     { 
      "theater": "theater A", 
      "schedule": [ 
       { 
        "movie": "Movie A", 
        "time": [ 
         "13:00", 
         "15:00", 
         "17:00", 
         "19:00", 
         "21:00" 
        ], 
        "price": "Rp.60,000" 
       }, 
       { 
        "movie": "Movie B", 
        "time": [ 
         "13:00", 
         "15:00", 
         "17:00", 
         "19:00", 
         "21:00" 
        ], 
        "price": "Rp.50,000" 
       } 
      ] 
     } 
     { 
      "theater": "theater B", 
      "schedule": [ 
       { 
        "movie": "Movie A", 
        "time": [ 
         "13:00", 
         "15:00", 
         "17:00", 
         "19:00", 
         "21:00" 
        ], 
        "price": "Rp.60,000" 
       }, 
       { 
        "movie": "Movie B", 
        "time": [ 
         "13:00", 
         "15:00", 
         "17:00", 
         "19:00", 
         "21:00" 
        ], 
        "price": "Rp.50,000" 
       } 
      ] 
     } 
    ] 
} 

還是得到了也許有可能的方式,使由影院排序的第一輸出JSON。任何想法?

回答

3

試試這個:

// JSONfrom api is stored in $apiJSON 
$apiArr = json_decode($apiJSON, true); 
$tmpArr = array(); 
foreach ($apiArr['data'] as $data) { 
    $movie = $data['movie']; 
    foreach ($data['schedule'] as $schedule) { 
     $tmpArr[$schedule['theater']][] = array('movie'=>$movie,'time'=>$schedule['time'],'price'=>$schedule['price']); 
    } 
} 

// Create new array structure 
$newArr = array(); 
foreach ($tmpArr as $theater=>$movies) { 
    $tmp = array(); 
    $tmp['theater'] = $theater; 
    $tmp['schedule'] = $movies; 
    $newArr['data'][] = $tmp; 
}