我有 3 个表,在加入名称并用此输出角色后
$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
echo json_encode($res);
}
我明白了
{"student_id":"1","student_name":"john","score_id":"1","score_type":"E","score_name":"England"}
{"student_id":"1","student_name":"john","score_id":"2","score_type":"B","score_name":"Brazil"}
现在我正在努力将它们转换成我想要的格式,客户端站点必须有这个
//json
[{
"student_id":"1",
"student_name":"john",
"scores": [{
"score_id":"1",
"score_type":"E",
"score_name":"England"
},{
"score_id":"2",
"score_type":"B",
"score_name":"Brazil"
}]
}]
挑战在于它与同一个人有重复的行。
最佳答案
使用数组 $encoded
处理输出,一旦构建完成,您就可以使用 JSON 打印它。
在此解决方案中,数组将按 student_id
索引,分数按 score_id
索引。如果是学生,则必须,如果是分数,则建议:
$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
// Student's details
$encoded[$res['student_id']] = array(
'student_id' => $res['student_id'],
'student_name' => $res['student_name'],
);
// Student's score details
$encoded[$res['student_id']]['scores'][$res['score_id']] = array(
'score_id' => $res['score_id'],
'score_type' => $res['score_type'],
'score_name' => $res['score_name'],
);
}
echo json_encode($encoded);
注意:这是一般性答案,因为我不知道 $res 中数据的确切结构。
关于PHP 将对象转换为数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040470/