Codeigniter到json bug修复

时间:2017-03-09 08:32:51

标签: json codeigniter

我为JSON api创建了一个简单的代码:

<?php
class Json extends CI_Controller {

    public function __construct()
    {
            parent::__construct();
            $this->load->helper('url_helper');
            $this->load->database();
    }
     public function index()
    {
        $user = $this->db->get('user');
        echo '{"user": [';

        foreach ($user->result() as $row)
        {
            echo "{";
                echo '"name" : "'. $row->user;
                echo '", "password" : "'. $row->password;
                echo '", "email" : "'. $row->email;
            echo '"},';
        }
        echo ']}';   
    }
}

结果是

{"user": [{"name" : "admin", "password" : "abcd", "email" : "deenjustin@gmail.com"},{"name" : "deenj", "password" : "dfgh", "email" : "deenj.effects@gmail.com"},]}

问题是逗号重复。请帮助修复错误。

2 个答案:

答案 0 :(得分:2)

json_encode将标准php数组转换为json。就像我说的那样,你对db的调用对我来说是错误的,但它似乎没有给你一个错误,所以我不知道那里发生了什么。但这就是我认为应该如何:

 public function __construct()
    {
            parent::__construct();
            $this->load->helper('url_helper');
            $this->load->database();
    }
     public function index()
    {
        $query = $this->db->get('user');
        $user = $query->result_array();
        echo json_encode($user);
}

除了我关于如何获取数据的问题,如果你可以将$ user转换为标准key =&gt; value数组,json_encode()函数将完成剩下的工作。

答案 1 :(得分:0)

在除第一个对象之外的对象前面加一个逗号:

public function __construct()
{
        parent::__construct();
        $this->load->helper('url_helper');
        $this->load->database();
}
 public function index()
{
    $user = $this->db->get('user');
    $index = 0;
    echo '{"user": [';

    foreach ($user->result() as $row)
    {
        if (!($index++)) echo ",";
        echo "{";
            echo '"name" : "'. $row->user;
            echo '", "password" : "'. $row->password;
            echo '", "email" : "'. $row->email;
        echo '"}';
    }
    echo ']}';   
}

}