如何在json中有一个列表和对象?

xytpbqjk  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(279)

我想要一个json来知道在“classid”:1中,“studentsid”:[1,2,3,4]在类中没有apear,我试图做一个查询,给我带来“classid”和“studentsid”,但是它们都在同一个表中,我不知道仅仅更改查询部分是否能带来我需要的东西。所以我的table会像:

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\u 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"}]}
ogsagwnx

ogsagwnx1#

只需一个查询,使用 GROUP_CONCAT 把同一个班的所有学生合并在一起。

SELECT ClassID, GROUP_CONCAT(StudentID) AS StudentsID
FROM School
GROUP BY ClassID
ORDER BY ClassID
``` `GROUP_CONCAT` 创建逗号分隔的字符串,可以使用 `explode()` 在php中将其转换为数组。

$list = array();
while ($row = mysqli_fetch_object($qry)) {
$list[] = array('ClassID' => $row['ClassID'], 'StudentsID' => explode(',', $row['StudentsID']);
}
echo json_encode($list);

相关问题