我正在尝试使用codeigniter制作并返回json数据。我想以这种格式接收数据
[
{
'title': 'this is title',
'desc': 'THis is desc'
},
{
'title': 'this is title',
'desc': 'THis is desc'
}
]
但我这样收到它
[[{"title":"this is title","desc":"this is desc"}],[{"title":"this is title","description":"this is desc"}]]
如何将此格式更改为以上格式?
这是我的代码
public function v1 () {
$this->load->model('model_jokes');
$jokes = $this->model_jokes->readJokes();
$arr = array();
foreach ($jokes as $joke) {
$arr[] = array(
array(
'title' => $joke->title,
'description' => $joke->joke
)
);
}
echo json_encode($arr);
}
答案 0 :(得分:1)
将foreach
内的作业设为
$arr[] = array(
'title' => $joke->title,
'description' => $joke->joke
);
否则,您将获得每个$joke
的多维数组。
答案 1 :(得分:1)
每次在循环中添加数组元素数组。而只是添加单个数组。
public function v1 () {
$this->load->model('model_jokes');
$jokes = $this->model_jokes->readJokes();
$arr = array();
foreach ($jokes as $joke) {
$arr[] = array(
'title' => $joke->title,
'description' => $joke->joke
);
}
echo json_encode($arr);
}
答案 2 :(得分:0)
尝试:
echo '<pre>'.json_encode($arr).'</pre>';