2014-03-24 48 views
0

我有一個名爲users的數據庫表,其中有一些鍵'userid,username,age',並且在這個表中還有一些記錄,我想讓它們像json一樣,請看看此如何在Codeingniter中響應json字符串

{ 
     "status":"1", 
     "msg":"success", 
     "userlist":[ 
     { 
     "userid":"1", 
     "username":"chard", 
     "age":"22" 
     }, 
     { 
     "userid":"2", 
     "username":"rose", 
     "age":"21" 
     }, 
     { 
     "userid":"3", 
     "username":"niki", 
     "age":"25" 
     } 
     ] 
} 

user_model.php文件,我寫

function get_users() 
{ 
$query = $this->db->get('users'); 
    return json_encode($query->row_array()); 
} 

user.php的控制器文件,我寫

function index_get() 
{ 
    $this->load->model('users_model'); 
    $query = $this->users_model->get_users(); 
echo $query; 
} 

我可以得到的結果,但它是一個錯誤的結果,僅此

{ "userid":"1", "username":"chard", "age":"22" } 

所以我應該如何解決這一問題?感謝

回答

2

嘗試$query->result_array()代替$query->row_array()

你的模型功能改變它:

function get_users() 
{ 
$query = $this->db->get('users'); 
return $query->result_array(); 
} 

並在控制器方法

function index_get() 
{ 
    $this->load->model('users_model'); 
    $users = $this->users_model->get_users(); 
    echo json_encode(array(
     'status' => 1, 
     'msg' => 'success', 
     'userlist' => $users 
    )); 
} 
0

試試這個:

function get_users() 
{ 
    $query = $this->db->get('users'); 
    return $query->result_array(); 
} 

function index_get() 
{ 
    $this->load->model('users_model'); 
    $users = $this->users_model->get_users(); 
    echo json_encode(array(
     'status' => 1, 
     'msg' => 'success', 
     'userlist' => $users 
    )); 
} 
0
You can use this: 

function get_users() 
{ 
      $dataarr = array(); 
    $res = array(); 
    $this->db->start_cache(); 

    $query = $this->db->get('users'); 

    $this->db->stop_cache(); 
    $this->db->flush_cache(); 
    $groups = array(); 

    if(!empty($res)) 
    { 
        foreach ($query->result() as $row) 
        { 
         $dataarr[]= 
      array(

      'userid' => $row['userid'], 
      'username' => $row['username'], 
      'age' => $row['age'] 
          ); 
        }      
    } 
    $query->free_result(); 
      $res = array(
          'status' => 1, 
          'msg' => 'success', 
          'userlist' => $dataarr 

         ); 


    return json_encode($res); 
    } 
0

我個人偏好的對象:

$data = $query->result(); 
echo json_encode($data); 

,將返回,而不是陣列(多維)的陣列對象的陣列。

您可以將參數值甚至傳遞給方法返回這些對象爲特定的類的實例:

$data = $query->result('User_model'); 

我傾向於只使用魔法常數,在任何情況下,我後來改變類名稱:

$data = $query->result(__CLASS__); 

這樣,你可以訪問你的對象在你的JavaScript回調是這樣的:

var data = yourResponse; 
yourResponse.userlist.forEach(function(user){ 
    alert(user.username); 
});