2013-06-30 51 views
0
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban"; 
$q=mysql_query($query); 
//echo $query; 
while($e=mysql_fetch_assoc($q)) 
      $output[]=$e; 
    print(json_encode($output)); 

從這個代碼,就會產生這樣的,mixare json,如何配置?

[ 
{"id":"1","latitude":"-77.036519","longitude":"77.036519","elevation":"0","title":"coba","distance":null,"has_detail_webpage":"0","webpage":"0","info":"0"}, 
{"id":"3","latitude":"12","longitude":"42","elevation":"21","title":"213","distance":"12","has_detail_webpage":"1","webpage":"12","info":"12"}, 
{"id":"32","latitude":"","longitude":"","elevation":null,"title":null,"distance":null,"has_detail_webpage":"1","webpage":null,"info":null} 
] 

但我想是這樣的,

{ "status": "OK", "num_results": 3, "results": 
[ { "id": "2833", "lat": "41.359288", "lng": "-73.646850", "elevation": "53", "title": "Target4", "distance": "1.756", "has_detail_page": "1", "webpage": "" }, 
    { "id": "2821", "lat": "41.359768", "lng": "-73.646870", "elevation": "0", "title": "Target2", "distance": "1.771", "has_detail_page": "0", "webpage": "" }, 
    { "id": "2829", "lat": "41.359820", "lng": "-73.646870", "elevation": "0", "title": "Target3", "distance": "1.545", "has_detail_page": "1", "webpage": "" } 
] } 

我該怎麼辦呢?

回答

1

獲取所有結果或逐行進行。選擇你自己。 En之後創建json數組。你也可能想看看你使用mysql_ *函數。因爲它們現在已被棄用。你真的應該切換到MySQli/PDO

$result = array(); 
while($row = mysql_fetch_assoc($q)) {  
$result[] = $row; 
} 

$output = array('status' => 'OK' , 'num_results' => count($result), 'results' => $result); 
echo json_encode($output); 
+0

謝謝,這是工作。 –

0

要添加你想要在你的json中的結構,首先你必須從PHP創建該結構,然後再將其編碼爲json。

$objects = array(); 
while ($r = mysql_fetch_associ($rs) { 
     $a = new stdClass(); 
     $a->status = $r['status']; 
     ... 
     $a->results = array('id' => $r['id']....) 
     $objects[] = $a; 
} 

echo json_encode($objects); 
+0

看來你缺少**> **在'$ A-結果=陣列( '身份證'=> $ R [ '身份證' ]'..應該是'$ a-> results' –

+0

@ShimonRachlenko謝謝 – DevZer0

+0

請問先生,請問是什麼? –

0
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban"; 

$q=mysql_query($query); 
$output = array(); 
if($q) { 
    $output['status'] = 'OK'; 
} 
$output['num_results'] = mysql_num_rows($q); 
while($e=mysql_fetch_assoc($q)) { 

$output['results'][]= array (
    'id' => $e['id'], 
    'lat' => $e['latitude'], 
    'lng' => $e['longitude'], 
    'elevation' => $e['elevation'], 
    'title' => $e['title'], 
    'distance' => $e['distance'], 
    'has_detail_page' => $e['has_detail_webpage'], 
    'webpage' => $e['webpage'], 
); 
} 
print(json_encode($output));