Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - convert mysql data into json object

I using codeigniter. I want to retrive data from database and convert it into JSON object not JSON array.I'm using following code

    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. 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

like image 675
Sangam Jung Gauli Avatar asked Apr 22 '26 20:04

Sangam Jung Gauli


2 Answers

Sangam try to understand the concept, check the following line:

$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 [];

like image 85
Mayank Pandeyz Avatar answered Apr 24 '26 08:04

Mayank Pandeyz


You want to 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.

Refer: PHP Array to Json Object

like image 32
Ramalingam Perumal Avatar answered Apr 24 '26 08:04

Ramalingam Perumal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!