简体   繁体   English

php - 将mysql数据转换为json对象

[英]php - convert mysql data into json object

I using codeigniter. 我使用codeigniter。 I want to retrive data from database and convert it into JSON object not JSON array.I'm using following code 我想从数据库中检索数据并将其转换为JSON对象而不是JSON数组。我正在使用以下代码

    public function json()
 {
        $content = $this->db->get('todolist'); //todolist table name
        $data = $content->result_array();
        echo json_encode($data);
 }

Above code is converting database into JSON array. 上面的代码是将数据库转换为JSON数组。 Output 产量

[{"todo_id":"1","todo_content":"Homework","date":"2016-05-05","iscomplete":null,"imagelink":"Lighthouse.jpg"},{"todo_id":"2","todo_content":"exam","date":"2015-04-21","iscomplete":null,"imagelink":"Desert.jpg"},{"todo_id":"3","todo_content":"Lab report","date":"2014-08-29","iscomplete":null,"imagelink":"FB_IMG_14700753538617403.jpg"}]

What will be best way to convert it into JSON object 将它转换为JSON对象的最佳方法是什么

Sangam try to understand the concept, check the following line: Sangam尝试理解这个概念,检查以下行:

$data = $content->result_array();    // $data is an array
echo json_encode($data);             // here you are converting it into an json object

Your $data array contains more than one index in it that's why the json object is having multiple {} inside [] ; 你的$data数组中包含多个索引,这就是为什么json对象在[]里面有多个{} ;

You want to json_encode($data, JSON_FORCE_OBJECT) . 你想要json_encode($data, JSON_FORCE_OBJECT)

The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array. 顾名思义, JSON_FORCE_OBJECT标志强制json输出为对象,即使它通常表示为数组也是如此。

Refer: PHP Array to Json Object 请参阅: PHP数组到Json对象

您可以使用JSON_FORCE_OBJECT查看下面的示例。

 echo json_encode($data, JSON_FORCE_OBJECT);

Assuming you're only getting one row back from your query. 假设您只从查询中获得一行。

change 更改

echo json_encode($data);

to

echo json_encode($data[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM