dsgrgaz321973284 2014-03-24 12:56
浏览 228
已采纳

如何在Codeigniter中响应json字符串

I have a database table named users with some keys 'userid, username, age', and also there are some records in this table, I want to get them like json, please look at this

   {
        "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 file, i write

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

user.php controller file, i write

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

I can get the result, but it's a wrong result, only this

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

so how should I fix this?

  • 写回答

4条回答 默认 最新

  • dongyi6845 2014-03-24 13:03
    关注

    Try $query->result_array() instead of $query->row_array()

    Your model function change it:

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

    And in controller method

    function index_get()
    {
        $this->load->model('users_model');
        $users = $this->users_model->get_users();
        echo json_encode(array(
            'status' => 1,
            'msg' => 'success',
            'userlist' => $users
        ));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?