2016-07-24 2 views
0

모든 결과를 mysql 테이블에서 가져 와서 Json 형식으로 변환하려고합니다. 각 행에는 공통 열 값 (movie_name)이 포함될 수 있습니다. 그 공통 분야로 결과를 그룹화하고 싶습니다.하나의 열 값으로 복수의 mysql 결과 그룹화

이이 쿼리 내 첫 번째 결과이다

$slots = SELECT movie_name,id as slot_id,screen_id,time,price FROM `slots`; 

결과 :

{ 
     "movies": [ 
      { 
       "movie_name": "iceage", 
       "slot_id": "142", 
       "screen_id": "45", 
       "time": "6.00", 
       "price": "204" 
      }, 
      { 
       "movie_name": "lights out", 
       "slot_id": "146", 
       "screen_id": "45", 
       "time": "11.00", 
       "price": "150" 
      }, 
      { 
       "movie_name": "lights out", 
       "slot_id": "147", 
       "screen_id": "45", 
       "time": "2.00", 
       "price": "103" 
      }, 
      { 
       "movie_name": "conjuring", 
       "slot_id": "148", 
       "screen_id": "45", 
       "time": "9.00", 
       "price": "500" 
      }, 
      { 
       "movie_name": "iceage", 
       "slot_id": "151", 
       "screen_id": "45", 
       "time": "", 
       "price": "11" 
      }, 
      { 
       "movie_name": "lights out", 
       "slot_id": "155", 
       "screen_id": "45", 
       "time": "11", 
       "price": "11" 
      } 
     ] 
} 

이 같은 결과 이상 변경하려면 : -

{ 
    "movies": [ 
      { 
       "movie_name": "lights out", 
       "slots":[ { 
        "slot_id": "146", 
        "screen_id": "45", 
        "time": "11.00", 
        "price": "150" 
       } 
       { 
        "slot_id": "147", 
        "screen_id": "45", 
        "time": "2.00", 
        "price": "103" 
       } 
       { 
        "slot_id": "155", 
        "screen_id": "45", 
        "time": "11", 
        "price": "11" 
       } 
       ] 
      }, 
      { 
       "movie_name": "conjuring", 
       "slots": { 
        "slot_id": "148", 
        "screen_id": "45", 
        "time": "9.00", 
        "price": "500" 
       } 
      }, 
      { 
       "movie_name": "iceage", 
       "slots":[ { 
        "slot_id": "142", 
        "screen_id": "45", 
        "time": "6.00", 
        "price": "204" 
       } 
       { 
        "slot_id": "151", 
        "screen_id": "45", 
        "time": "", 
        "price": "11" 
       } 
       ] 
      }, 
     ] 
    } 

어떻게 변경해야 내 결과를 얻기위한 쿼리. 이 PHP 코드를 사용해 보았습니다.

      foreach ($slots as $row) { 
           $movie_name = $row['movie_name']; 
           if (!isset($groups[$movie_name])) { 
            $groups[$movie_name] = array(); 
           } 
          $groups[$movie_name][] = $row; 
          } 

하지만 결과가 좋지 않습니다. 도와주세요. 감사합니다 ..

답변

0
$json_arr = array("movies"=>array()); 
foreach ($slots as $slot) { 
    $json_arr['movies'][$slot["movie_name"]]['movie_name'] = $slot["movie_name"]; 
    $json_arr['movies'][$slot["movie_name"]]['slots'][] = array (
     "slot_id" => $slot["slot_id"], 
     "screen_id" => $slot["screen_id"], 
     "time" => $slot["time"], 
     "price" => $slot["price"] 
    ); 
}