我想要一个JSON来知道在“ ClassID”:1中,“ StudentsID”:[1,2,3,4]没有出现在该类中,并且我正在尝试执行一个查询带给我“ ClassID”和“ StudentsID”,但它们都在同一张表中,我不知道是否仅更改查询部分就能满足我的需求。所以我的桌子会像这样:
Table: School
ClassID | StudentsID
1 1
1 2
2 2
2 3
2 4
2 5
3 1
3 2
因此,您在“ ClassID”:1中看到的“ StudentsID”:[1和2]丢失了。我需要的JSON是这样的:
{"Misses":[{"classID":1,"StudentsMissing":[1,2]},{"classID":2,"StudentsMissing":[2,3,4,5]}]}
我已经尝试过arraypush,array_merge了,但是由于我是PHP新手,所以我无法执行这样的JSON。
我所能获得的就是这个JSON:
{"Misses":[{"classID":"1"}]}{"Students":[{"StudentsMissing":"1"}]}
我尝试过的代码是这样的:
<?php
$list = array();
$bd = mysqli_connect("localhost","root","","web");
if ($bd) {
$qry = mysqli_query($bd, "SELECT ClassID FROM School ORDER BY ClassID");
$qry1 = mysqli_query($bd, "SELECT StudentID FROM School");
if (mysqli_num_rows($qry) > 0){
while ($row = mysqli_fetch_object ($qry)){
$list[] = $row;
}
$output = new StdClass();
$output->ClassID = $list;
echo json_encode($output);
}
$list = array();
if (mysqli_num_rows($qry1) > 0){
while ($row = mysqli_fetch_object ($qry1)){
$list[] = $row;
}
$output = new StdClass();
$output->Students = $list;
echo json_encode($output);
}
else {
echo "Erro";
}
}
else {
echo "Erro";
}
我有一个像这样的JSON:
{"Misses":[{"classID":"1"},{"classID":"2"},{"classID":"3"}]}{"Students":[{"StudentsMissing":"1"},{"StudentsMissing":"2"},{"StudentsMissing":"3"}]}
答案 0 :(得分:1)
使用GROUP_CONCAT
将一个班级的所有学生合并在一起,用一个查询来做。
SELECT ClassID, GROUP_CONCAT(StudentID) AS StudentsID
FROM School
GROUP BY ClassID
ORDER BY ClassID
GROUP_CONCAT
创建一个逗号分隔的字符串,您可以在PHP中使用explode()
将其转换为数组。
$list = array();
while ($row = mysqli_fetch_object($qry)) {
$list[] = array('ClassID' => $row['ClassID'], 'StudentsID' => explode(',', $row['StudentsID']);
}
echo json_encode($list);