2016-07-24 9 views
0

私はすべての結果フォームをmysqlテーブルからフェッチし、Jsonフォーマットに変換しようとしています。各行には、共通の列値(movie_name)を含めることができます。私は共通のフィールドで結果をグループ化したい。複数のmysql結果を1つの列の値でグループ化する

これは、このクエリ

$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"] 
    ); 
} 
関連する問題