我正在开发一个codeigniter应用程序。我需要以这种格式返回的json数据。
{
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"}
]
}
然而,当返回数据时,我只有这种格式
[{"id":"1","text":"test"},
{"id":"2","text":"kabita123"},
{"id":"3","text":"purnima"},
{"id":"4","text":"raju123"},
{"id":"5","text":"saad123"},
{"id":"12","text":"apf123"}]
我在哪里做错了?我用来生成json数据的代码是
$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 );
答案 0 :(得分:3)
变化:
echo json_encode( $user_arr );
为:
echo json_encode( array('options' => $user_arr) );