2017-07-09 69 views
0

我遇到了一些問題,從我的SQL查詢中獲取正確的JSON輸出。基本上我正在努力的是獲得一組選項對象,而不是單一選項對象。將SQL查詢結果映射到PHP中的JSON

$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup 
     INNER JOIN matchup_option 
     ON matchup_option.matchupID= matchup.matchupID;'; 

$attachments = $db->query($query); 
$data = array(); 
while ($attachment = $db->fetch_array($attachments)){ 
    $data[] = array (
     'id' => $attachment['matchupID'], 
     'options' => array(
      array (
       "name" => $attachment['player_name'], 
       "playerid" => $attachment['player_id'] 
      ) 
     ) 
    ); 
    //VAR_DUMP($attachment); 
} 
$data = array("matchup"=>$data); 
print json_encode($data); 

給了我這樣的輸出:

{ 
"matchup":[ 
    { 
    "id":"111222", 
    "options":[ 
     { 
      "name":"111", 
      "playerid":"111" 
     } 
    ] 
    }, 
    { 
    "id":"111222", 
    "options":[ 
     { 
      "name":"222", 
      "playerid":"222" 
     } 
    ] 
    } 
] 
} 

這裏就是我試圖去:

{ 
"matchup":[ 
    { 
    "id":"111222", 
    "options":[ 
     { 
      "name":"111", 
      "playerid":"111" 
     }, 
     { 
      "name":"222", 
      "playerid":"222" 
     } 
    ] 
    } 
] 
} 

我想遵循最佳做法以及結構這如果有更好的方法去解決這個問題,請告訴我!

+0

請問* ID *是相同的所有行? –

回答

1

您需要存儲$attachment['matchupID']作爲$data數組鍵:

$data = array(); 
while ($attachment = $db->fetch_array($attachments)){ 
    if (!isset($data[$attachment['matchupID']])) { 
     $data[$attachment['matchupID']] = array (
      'id' => $attachment['matchupID'], 
      'options' => array() 
     ); 
    } 
    $data[$attachment['matchupID']]['options'][] = array (
     "name" => $attachment['player_name'], 
     "playerid" => $attachment['player_id'] 
    ); 
} 

// use `array_values` to reindex `$data` 
$data = array("matchup" => array_values($data)); 
print json_encode($data); 
+0

解決方案總是非常簡單!謝謝,我的朋友。 – user3344880

相關問題