2017-02-27 55 views
0

我想讓使用數據的JSON文件從我的MySQL數據庫。我怎樣才能包括PHP中的簡單數組的關聯數組?

我正在使用下面的代碼來創建一個json文件。

<?php 

$con = mysqli_connect('localhost','root','','mydb1'); 
$return_arr = array(); 
$sql = "select * from questions"; 
$res = mysqli_query($con,$sql); 
while($row = mysqli_fetch_assoc($res)){ 
$row_array['id'] = $row['id']; 
$row_array['ques'] = $row['ques']; 
$row_array['ans'] = $row['ans']; 
array_push($return_arr,$row_array); 
} 
mysqli_close($con); 
$b = json_encode($return_arr); 
$f = fopen("test.json","w"); 
fwrite($f,$b); 
fclose($f); 


?> 

這是給我下面的輸出:

[{"id":"1","ques":"New Delhi is capital of India?","ans":"1"},{"id":"2","ques":"India has 5 neighboring countries.","ans":"0"}] 

但我想我的結果一樣:

{"questions" : {"question" : [{"id":"1","ques":"New Delhi is capital of India?","ans":"1"},{"id":"2","ques":"India has 5 neighboring countries.","ans":"0"}]} 

,這樣我可以在android.How正確使用它我可以做這個? 任何人都可以請幫忙嗎?

或者你可以請我幫助我如何在不改變我的數組的情況下在android中使用它。

在此先感謝。

回答

4

很簡單只是改變這一行

$b = json_encode($return_arr); 

這一行

$b = json_encode(['questions' => ['questions' => $return_arr]]); 

當你保存JSON文件你保存爲數組OB的對象,當你想將其保存爲一個關鍵值對,那麼你必須指定密鑰。

另外一個快速提示,如果你想你的JSON漂亮的輸出,你可以使用JSON_PRETTY_PRINT作爲你的第二個參數是這樣

$b = json_encode(['questions' => $return_arr], JSON_PRETTY_PRINT); 

在這裏看到http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-parameters

+0

能否請你檢查我編輯的問題,我改變了它一點點。 我需要一點點不同的JSON。謝謝 – BugAdder

+0

非常感謝。 你節省了我的一天。 :) – BugAdder

相關問題