How to add a separate field to a record in a database table for JSON output
Table user has two fields, Id,name
Table User_friend has three fields, 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 ();
Dear friends, I would like to output the following JSON format, how should I do?
{
"User": {
"id": "46",
"Name": "John",
"Userfriend": [{
"id": "13",
"UserId": "46",
"friendID": "43"
},
{
"id": "15",
"UserId": "46",
"friendID": "44"
}
]
}
}
------to solve the idea----------------------
Print_r ($userfriend);
Look what it is.
------to solve the idea----------------------
Give it a try.
$user [' Userfriend ']= $userfriend;
$data [' user ']= $user;
echo Json_encode ($data);
------to solve the idea----------------------
My thoughts are:
1. Stitching JSON
1). loop $user, nested loop $userfriend
2. Reorganizing an array
1). Two-table joint check
2). Looping constructs a new array
Extra:
Json_encode () Note coding UTF-8
------to solve the idea----------------------
That's all you can do.
$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);
------to solve the idea----------------------
Remove all users first, and the Foreach loop takes out each user's friend and saves it in a value