How to add a single field to a record in a database table for JSON output

Source: Internet
Author: User
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
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.