2010-03-09 44 views
12

我想用json_encode將模型查詢轉換爲json,但它不起作用。但是它有一個普通的陣列。將codeigniter查詢轉換爲json?

$arr = array("one", "two", "three"); 
     $data["json"] = json_encode($arr); 

輸出

<?php echo "var arr=".$json.";"; ?> 
var arr=["one","two","three"]; 

但是,當我嘗試轉換查詢笨拋出一個錯誤。那是什麼? 這是錯誤消息:

甲PHP錯誤遇到嚴重性: 警告信息:[JSON] (php_json_encode)類型不受支持, 編碼爲空

並將轉換後的「查詢「結果=我的意思是模型的方法是這樣的:

{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null} 

我嘗試做這樣的

$posts = $this->Posts_model->SelectAll(); 
     $data["posts"] = json_encode($posts); 

順便說一句,當我做沒有json_encode的模型和方法工作得很好。

東西我可以做的錯,但問題是什麼?

+0

你能後不工作的代碼?我不明白你爲什麼要把你的查詢轉換成json。你不應該將結果數據轉換成json嗎? –

+0

如果出現錯誤,您可能希望與我們分享錯誤。 ;-) –

+0

你可以請發佈錯誤信息? – Pedro

回答

22

您似乎試圖編碼CodeIgniter數據庫結果對象而不是結果數組。數據庫結果對象充當遊標到結果集中的包裝。您應該從結果對象中獲取結果數組,然後對其進行編碼。

你的模型代碼看起來是這樣的:

function SelectAll() 
{ 
    $sql = 'SELECT * FROM posts'; 
    // Return the result object 
    return $this->db->query($sql); 
} 

應該更多這樣的:

function SelectAll() 
{ 
    $sql = 'SELECT * FROM posts'; 
    $query = $this->db->query($sql); 
    // Fetch the result array from the result object and return it 
    return $query->result(); 
} 

這將返回您可以在JSON編碼對象的數組。

原因你正在試圖編碼結果對象的錯誤是因爲它無法在JSON編碼一個resource成員變量。這個資源變量實際上是將光標放入結果集中。

+0

非常感謝。我對codeigniter很陌生,留下來學習它的API,但現在它更加有趣。 – marko

+0

沒問題。樂意效勞 :-) –

1
public function lastActivity() 
{ 
    header("Content-Type: application/json"); 
    $this->db->select('*'); 
    $this->db->from('table_name'); 
    $query = $this->db->get(); 

    return json_encode($query->result()); 
} 
0

這裏是工作的解決方案:

  $json_data = $this->home_model->home_getall(); 
      $arr = array(); 
      foreach ($json_data as $results) { 
      $arr[] = array(
        'id' => $results->id, 
        'text' => $results->name 
        ); 
      } 
     //save data mysql data in json encode format  
      $data['select2data'] = json_encode($arr); 
0

模型(POST):

function SelectAll() 
{ 
    $this->db->select('*'); 
    $this->db->from('post'); 
    $query = $this->db->get(); 
    return $query; 
} 

控制器:

$data['post'] = $this->post->SelectAll()->result_array(); 
echo json_encode($data); 

結果:

{"post":[{"id":"5","name":"name_of_post"}]} 
1

按照最新CI標準用在你的控制器文件下面的代碼:

$this->output->set_content_type('application/json')->set_output(json_encode($arr));