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 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建