My query returns the following:
post_id post_type post_text
1 text bla1
2 pic bla2
3 text bla3
I loop through this result as follows:
$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;
If I json_encode and output from my controller I get this:
{
"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",
}]
}
}
However if a post has comments, my query returns
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
How should I set up the foreach loop to build an array that will output JSON like this?
{
"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",
}],
}]
}
}
This JSON is consumed on Secha framework as follows:
proxy: {
type: 'jsonp',
url: 'http://myurl',
reader: {
type: 'json',
rootProperty: 'stream.posts'
}
}