我在 mysql 中有下表。 1)用户
userid username college
1 robert sarauniversity
2 albert oxford
2)UserDetails
userid subjectid
1 1
1 2
2 3
1 4
2 1
3)subjectdetails
subjectid subjectname subjectteacher
1 basic science pro. vengaskar
2 advance mathematics pro. richard
3 history pro. michale
4 geography pro. renuka
我需要以下 json 数据
[
{
id:1
username:robert
subjects:[
{
subjectname:pro. geography ,
subject teacher:algebra
},
{
subjectname:pro. vengaskar,
subject teacher:pro. renuka
}
]
},
{
id:2
username:albert
subjects:[
{
subjectname:history ,
subject teacher: pro. michale
},
{
subjectname:basic science,
subject teacher: pro. vengaskar
}
]
}
}
我已经开发过几次json Rest api,但这次是带有json数组的对象的json数组。 我很困惑如何迭代内容并获得最终所需的 json。 我不会粘贴 php 代码,因为没有任何帮助我。 很遗憾,我花了两天时间,但仍处于开始阶段......
最佳答案
通过这样的查询得到结果
SELECT A.userid,A.username, C.subjectname,C.subjectteacher FROM `A` AS users INNER JOIN `UserDetails` AS B on A.userid = b.userid INNER JOIN `subjectdetails` AS C on C.subjectid = B.subjectid
然后在循环中以以下格式操作结果
$arr = array (
array (
"id" => "1",
"username" => "Robert",
"subjects" => array (
array (
"subjectname" => "pro. geography",
"subject teacher" => "algebra"
)
)
)
);
echo json_encode ( $arr );
输出
[
{
"id": "1",
"username": "Robert",
"subjects": [
{
"subjectname": "pro. geography",
"subject teacher": "algebra"
}
]
}
]
关于php - 从两个表创建自定义 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20470093/