2011-08-17 65 views
2

我試圖建立從一個PHP數組 JSON數組這是我在我的控制器功能用PHP echo語句生成JSON

function latest_pheeds() { 
      if($this->isLogged() == true) { 
      $this->load->model('pheed_model'); 
      $data = $this->pheed_model->get_latest_pheeds(); 
      $last = end($data); 
      echo "["; 
       for($i = 0; $i < count($data); $i++) { 
        echo '{"user_id":"'.$data[$i][0]['user_id'].'",'; 
        echo '"pheed_id":"'.$data[$i][0]['pheed_id'].'",'; 
        echo '"pheed":"'.$data[$i][0]['pheed'].'",'; 
        echo '"datetime":"'.$data[$i][0]['datetime'].'",'; 
         if($i == count($data)) { 
         echo '"comments":"'.$data[$i][0]['comments'].'"}'; 
         }else { 
          echo '"comments":"'.$data[$i][0]['comments'].'"},'; 
         } 
        } 

       echo "]"; 
      } 
      return false; 
    } 

它返回一個JSON數組這樣

[{"user_id":"9","pheed_id":"2","pheed":"This is my first real pheed, its got potential ","datetime":"1313188898","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"10","pheed":"Thank God for stackoverflow.com ","datetime":"1313358605","comments":"0"},] 

但我似乎無法訪問它與jquery

+1

你最後需要那個逗號嗎 –

+0

你如何用jQuery訪問它? – labue

+0

正如所建議的那樣,最後的逗號打破了json解碼。另外,正如@derekerdmann的提問者所建議的那樣,爲此使用json_encode,這就是它的意思。 – sberry

回答

1

已經投了@derekerdmann,但想到我要補充...

你的代碼將工作,如果你改變:

if($i == count($data)) { 

if($i == count($data) - 1) { 

但是,不要't這樣做。如果您只是將$data陣列的每個成員的所有內容都放入json中,那麼您應該只能使用json_encode($data)。如果您只抽取某些部分,則建立一個已過濾數據的輔助數組,然後json_encode

function latest_pheeds() { 
    if($this->isLogged() == true) { 
     $this->load->model('pheed_model'); 
     $data = $this->pheed_model->get_latest_pheeds(); 
     $filtered_items = array(); 
     foreach ($data as $member) { 
      $filtered_item = array(); 
      $filtered_item['user_id'] = $member['user_id']; 
      $filtered_item['pheed_id'] = $member['pheed_id']; 
      ... 
      ... 
      $filtered_items[] = $filtered_item; 
     } 
     echo json_encode($filtered_items); 
    } 
    return false; 
} 
+0

謝謝,它得到它的工作 – MrFoh

8

我相信問題在於數組結尾的尾隨逗號。

而不是嘗試自己編碼,請使用PHP的json_encode函數。它經過多次測試和驗證,因此您不必重新發明輪子。

+0

是的,我試過了,但它仍然無法通過jquery讀取。 – MrFoh

+2

@MrFoh:這是一個不同的問題。我會建議設置您的標題,以表明您正在返回JSON。 – TehShrike