Home >Backend Development >PHP Tutorial >怎么将数据库表的一条记录中增加一个单独的字段来进行json输出

怎么将数据库表的一条记录中增加一个单独的字段来进行json输出

WBOY
WBOYOriginal
2016-06-13 12:25:191280browse

如何将数据库表的一条记录中增加一个单独的字段来进行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 />

------解决思路----------------------
先取出所有用户,foreach循环取出每个用户的朋友,在保存到一个数值里面

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn