如何将数据库表的一条记录中增加一个单独的字段来进行json输出
表user有两个字段,id,name
表user_friend有三个字段,id,userid,friendid
$query = $this->db->query('SELECT * FROM user where id=46' );
$user=$query->row();
$queryfriend= $this->db->query('SELECT * FROM user_friend where userid='.$user->id );
$userfriend=$queryfriend->result();
各位亲,请问下我要输出如下的json格式,应该怎样操作?
{
"user": {
"id": "46",
"name": "john",
"userfriend": [ {
"id": "13",
"userId": "46",
"friendId": "43"
},
{
"id": "15",
"userId": "46",
"friendId": "44"
}
]
}
}
------解决思路----------------------
print_r($userfriend);
看看都是什么
------解决思路----------------------
这样试试
$user['userfriend']=$userfriend;
$data['user']=$user;
echo json_encode($data);
------解决思路----------------------
我的想法:
1.拼接json
1).循环$user,嵌套循环$userfriend
2.重组数组
1).两表联查
2).循环构造新数组
额外:
json_encode()注意编码UTF-8
------解决思路----------------------
这样就可以了。
<br />$query = $this->db->query('SELECT * FROM user where id=46' );<br />$user=$query->row();<br />$queryfriend= $this->db->query('SELECT * FROM user_friend where userid='.$user->id );<br />$userfriend=$queryfriend->result();<br /><br />$data = array();<br />$data['user']['id'] = $user[0]['id'];<br />$data['user']['name'] = $user[0]['name'];<br />$data['user']['userfriend'] = $userfriend;<br /><br />echo json_encode($data);<br />