我的查询返回以下内容:
post_id post_type post_text
1 text bla1
2 pic bla2
3 text bla3
我循环遍历这个结果如下:
$posts = array();
foreach ($query->result() as $row) {
$post = array();
$post['post_id'] = $row->post_id;
$post['post_type'] = $row->post_type;
$post['post_text'] = $row->post_text;
$posts[] = $post;
}
$data['posts'] = $posts;
return $data;
如果我json_encode
和我的控制器的输出我得到这个:
{
"stream": {
"posts": [{
"post_id": "1",
"post_type": "text",
"post_text": "bla1",
},
{
"post_id": "2",
"post_type": "pic",
"post_text": "bla2",
},
{
"post_id": "3",
"post_type": "text",
"post_text": "bla3",
}]
}
}
但是,如果帖子有评论,我的查询会返回
post_id post_type post_text comment_id comment_text
1 text bla1 7 asd
1 text bla1 8 sdf
2 pic bla2
3 text bla3 10 rty
3 text bla3 11 yuo
我应该如何设置 foreach 循环来构建一个将像这样输出 JSON 的数组?
{
"stream": {
"posts": [{
"post_id": "1",
"post_type": "text",
"post_text": "bla1",
"comment": [{
"comment_id": "7",
"comment_text": "asd",
},
{
"comment_id": "8",
"comment_text": "sdf",
}],
},
{
"post_id": "2",
"post_type": "pic",
"post_text": "bla2",
},
{
"post_id": "3",
"post_type": "text",
"post_text": "bla3",
"comment": [{
"comment_id": "10",
"comment_text": "rty",
},
{
"comment_id": "11",
"comment_text": "yuo",
}],
}]
}
}
这个 JSON 在 Secha 框架上使用如下:
proxy: {
type: 'jsonp',
url: 'http://myurl',
reader: {
type: 'json',
rootProperty: 'stream.posts'
}
}