Heim >Backend-Entwicklung >PHP-Tutorial >如何将数据库表的一条记录中增加一个单独的字段来进行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);
看看都是什么
print_r($userfriend)结果如下;
Array ( [0] => stdClass Object ( [id] => 13 [userId] => 46 [friendId] => 43 ) [1] => stdClass Object ( [id] => 15 [userId] => 46 [friendId] => 44 ) [2] => stdClass Object ( [id] => 16 [userId] => 46 [friendId] => 45 ) )
userfriend输出数据库查出来对应的[]格式就行了
这样试试
$user['userfriend']=$userfriend;
$data['user']=$user;
echo json_encode($data);
$user['userfriend']=$userfriend;
$data['user']=$user;
echo json_encode($data);
输出如下,不是我想要的格式
{
"user": {
"0": {
"id": "45",
"nickName": "Jerry",
"gender": "1",
"birthday": "2000年10月01日",
"avatar": "upload/user/45/avatar/0434541421051694278.jpg",
},
"userfriend": [
{
"id": "5",
"userId": "45",
"friendId": "3",
"endTime": "1426745161"
},
{
"id": "7",
"userId": "45",
"friendId": "5",
"endTime": "1426745161"
},
{
"id": "9",
"userId": "45",
"friendId": "44",
"endTime": "1426745161"
},
{
"id": "10",
"userId": "45",
"friendId": "46",
"endTime": "1426745161"
}
]
}
}
我的想法:
1.拼接json
1).循环$user,嵌套循环$userfriend
2.重组数组
1).两表联查
2).循环构造新数组
额外:
json_encode()注意编码UTF-8
这样就可以了。
$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();$data = array();$data['user']['id'] = $user[0]['id'];$data['user']['name'] = $user[0]['name'];$data['user']['userfriend'] = $userfriend;echo json_encode($data);
先取出所有用户,foreach循环取出每个用户的朋友,在保存到一个数值里面
正确的代码如下,感谢各位
$user = $query->result_array();
$data = $user[0];
$data['userfriend'] = $userfriend;
// $result = array('result' => array('status' => '1', 'message' => '登陆成功', 'user' => $data));
$result = array( 'user' => $data);
echo json_encode($result);