2016-11-18 33 views
1

我如何編碼兩個數組,從2個不同的表在我的數據庫中檢索數據,並在1個JSON響應進行編碼2一個JSON對象,在不同的陣列中選擇查詢

Here is my php 
    $sql = "select * from schedule;"; 
$sql1 = "select * from matches;"; 
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name); 

$result = mysqli_query($con,$sql); 
$result1 = mysqli_query($con,$sql1); 


$response = array(); 
while($row=mysqli_fetch_array($result)) 
{ 
array_push($response, array("n_name"=>$row[1],"start"=>$row[4],"end"=>$row[5],"venue"=>$row[6])); 

} 

$data= array(); 
while($row=mysqli_fetch_array($result1)) 
{ 
array_push($data, array("teamone"=>$row[1], "teamtwo"=>$row[2], "s_name"=>$row[10])); 
} 



echo json_encode (array("server_response"=>$response, $data)); 





mysqli_close($con); 
?> 

什麼,我想是這樣的

{ 
    "server_response": [{ 
     "n_name": null, 
     "start": "2016-11-09 00:00:00", 
     "end": "2016-11-16 00:00:00", 
     "venue": "aaaaaa", 
     "teamone": "aaa", 
     "teamtwo": "bbb", 
     "s_name": "" 
    }] 
    } 

相反,我得到這樣的

{ 
     "server_response": [{ 
      "n_name": null, 
      "start": "2016-11-09 00:00:00", 
      "end": "2016-11-16 00:00:00", 
      "venue": "aaaaaa" 
     }], 
     "0": [{ 
      "teamone": "aaa", 
      "teamtwo": "bbb", 
      "s_name": "" 
     }] 
    } 

有人可以幫助我。謝謝!

+0

在2個表中有任何關係? –

+0

是的,他們有先生。如果他們沒有關係,是不是可以將它們結合起來? – orange

+0

可能但不能使用'JOIN' –

回答

0
$response = array(); 
while($row=mysqli_fetch_array($result)) 
{ 
    $response['server_response']["n_name"] = $row[1]; 
    $response['server_response']["start"] = $row[4]; 
    $response['server_response']["end"] = $row[5]; 
    $response['server_response']["venue"] = $row[6]; 
} 


while($row=mysqli_fetch_array($result1)) 
{ 
    $response['server_response']["teamone"] = $row[1]; 
    $response['server_response']["teamtwo"] = $row[2]; 
    $response['server_response']["s_name"] = $row[10]; 
} 

echo json_encode ($response); 
+0

你可以顯示你的2表列名稱嗎? –

+0

非常感謝您的先生Razib! – orange

0

echo json_encode(array(「server_response」=> array_merge($ response,$ data)));

回波json_encode(陣列( 「server_response」=> $響應+ $數據)); //如果兩個陣列中存在相同密鑰的風險

+0

先生陣列合併遊戲我{「schedule_response」:[{「start」:「2016-11-10 00:00:00」,「end」:「2016-11-04 00:00:00」,「地點「:」bbbb「},{」teamone「:」aaa「,」teamtwo「:」bbb「,」s_name「:」「}]}我需要的是{」schedule_response「:[{」start「:」2016 -11-10 00:00:00「,」結束「:」2016-11-04 00:00:00「,」場地「:」bbbb「}」teamone「:」aaa「,」teamtwo「:」bbb 「,」s_name「:」「}]感謝的方式:) – orange