2012-05-23 52 views
0

我返回的數組以無效的奇怪格式返回。至少不在我的AJAX體驗中。我返回的數組沒有作爲對象返回

function get_within($latitude, $longitude) { 
global $pdo; 

    // $lat = $latitude; 
    // $long = $longitude; 
    // $long = '-70.98245279999999'; 
    // $lat = '41.98156549999999'; 

    $stmt = $pdo->prepare("SELECT menu_id, latitude, longitude (acos(
      cos(radians(".$latitude." )) * 
      cos(radians(latitude)) * 
      cos(radians(".$longitude.") - radians(longitude)) + 
      sin(radians(".$latitude.")) * sin(radians(latitude))))*.621371192 
as dis from pages where 1 ORDER BY `dis` ASC LIMIT 10"); 

$stmt->execute(array()); 

return $stmt->fetchAll(PDO::FETCH_OBJ); 

我使用上述功能發出了AJAX請求。我需要它返回一個對象,但它只是返回一個數組是這樣的:

[{"id":"26","subject_id":"5","menu_name":"Bobby Byrne's Food & Pub\u200e","position":"1","visible":"1","content":"Bobby Byrne's Restaurant & Pub\u200e\r\n65 Massachusetts 6A, Sandwich, MA\r\n(508) 888-6088","longitude":"-70.508598","latitude":" 41.765754","dis":"0.00245126419033985"}]

什麼是錯的,我怎麼能在對象中找回我的查詢正確使用?

+0

我想你'echo json_encode(get_within(x,y));'? – Bergi

回答

0

由於@DanArmstrong指出,沒有什麼奇怪的或無效的關於返回的JSON數組。 Per the documentationPDOStatement::fetchAll應該返回一個數組 - 它是 - 當你將數組編碼爲JSON時,它使用array notation,這是有效的JSON和你在這裏看到的。

如果你想有一個JSON對象,而不是數組,你需要:

  1. 在服務器端得到一個項目出由fetchAll返回的數組和編碼 值(例如json_encode($results[0]))代替編碼整個返回的 陣列或
  2. 在客戶端從解碼陣列中獲取一個項目,例如JSON.parse(data)[0]
+0

啊!而已!現在唯一的事情是我無法弄清楚如何從對象中獲得全部10個結果。 $ locations = json_encode($ results [0]);給我第一個對象。我怎樣才能得到它們?一些類型的循環? – BenRacicot

相關問題