php - Manipulate JSON

710

I am developing a codeigniter application. I need the returned json data in this format.

 {
        options: [
    {id:"1",text:"test"},
    {id:"2",text:"kabita123"},
    {id:"3",text:"purnima"},
    {id:"4",text:"raju123"},
    {id:"5",text:"saad123"},
    {id:"12",text:"apf123"}
        ]
    }

However, when returning the data, I only have it in this format

[{"id":"1","text":"test"},
{"id":"2","text":"kabita123"},
{"id":"3","text":"purnima"},
{"id":"4","text":"raju123"},
{"id":"5","text":"saad123"},
{"id":"12","text":"apf123"}]

Where am I doing it wrong ? The code I am using to generate the json data is

        $users = $this->user_m->get_all();  
        $user_arr = [];
        $i=0;
        foreach ($users as $user) {
            $user_arr[$i] = new stdClass();
            $user_arr[$i]->id = $user->id;
            $user_arr[$i]->text = $user->username;
            $i++;
        }
       //add the header here
        header('Content-Type: application/json');
        echo json_encode( $user_arr );
469

Answer

Solution:

Change:

echo json_encode( $user_arr );

to:

echo json_encode( array('options' => $user_arr) );

People are also looking for solutions to the problem: php - grant permission to a new role in Laravel 5

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.