2013-07-31 166 views
1

我想從MySQL表中獲取數據並以下面的格式創建JSON輸出。PHP MySQL JSON輸出

{ 
    markers: [ 
    { 
     latitude: 57.7973333, 
     longitude: 12.0502107, 
     title: "Angered", 
     content: "Representing :)" 
    }, 
    { 
     latitude: 57.6969943, 
     longitude: 11.9865, 
     title: "Gothenburg", 
     content: "Swedens second largest city" 
    } 
    ] 
} 

這裏是我使用生成JSON

$model = array(); 

    $query = "SELECT title, content, lat, lng FROM locations_tbl"; 

    //Get records from database 
    $result = mysql_query($query, $con); 

    if(mysql_num_rows($result)) { 
     while($e = mysql_fetch_assoc($result)) { 
      $model['title'][]  = $e['title']; 
      $model['content'][] = $e['content']; 
      $model['lat'][]  = $e['lat']; 
      $model['lng'][]  = $e['lng']; 
     } 
    } 

    header('Content-type: application/json'); 
    print json_encode(array('marker'=>$model)); 

下面是我得到與上面的代碼輸出的PHP:

{ 
    marker: { 
     title: [ 
      "Marker 1", 
      "Marker 2", 
      "Marker 3", 
      "Marker 4", 
      "Marker 5" 
     ], 
     content: [ 
      "Text 1", 
      "Text 2", 
      "Text 3", 
      "Text 4", 
      "Text 5" 
     ], 
     lat: [ 
      "46.99065400", 
      "47.03520400", 
      "47.20387700", 
      "47.62574900", 
      "47.43443400" 
     ], 
     lng: [ 
      "-122.92164800", 
      "-122.81614600", 
      "-122.24486400", 
      "-122.14453800", 
      "-122.46088200" 
     ] 
    } 
} 

有什麼建議?

+0

@ user2495292你的JSON不是有效的,你可以使用這個驗證器來查看有效性http://jsonlint.com/ –

+0

我糾正了你的JSON,檢查這是否是正確的JSON? http://pastebin.com/BeLxGZKy –

回答

3

這樣創建數組:

$i = 0; 
    while($e = mysql_fetch_assoc($result)) { 
     $model[$i]['title']  = $e['title']; 
     $model[$i]['content']  = $e['content']; 
     $model[$i]['lat']   = $e['lat']; 
     $model[$i]['lng']   = $e['lng']; 
     $i++; 
    } 
+0

謝謝修復它! –

2

試試這個

 $i = 0; 
     while($e = mysql_fetch_assoc($result)) { 
      $model[$i]['title']  = $e['title']; 
      $model[$i]['content'] = $e['content']; 
      $model[$i]['lat']  = $e['lat']; 
      $model[$i]['lng']  = $e['lng']; 
      $i++; 
     } 

我希望這將有助於

2

你從來沒有真正爲每個標記創建一個新的數組:

$model = array("markers" => array()); 
if(mysql_num_rows($result)) { 
    while($e = mysql_fetch_assoc($result)) { 
     $marker = array(); 
     $marker['title'] = $e['title']; 
     $marker['content'] = $e['content']; 
     $marker['lat']  = $e['lat']; 
     $marker['lng']  = $e['lng']; 
     $model["markers"][] = $marker; 
    } 
}