Php 如何在JSON中包含列表和对象?
我想让JSON知道在“ClassID”:1,“StudentsID”:[1,2,3,4]在类中没有出现,我试图做一个查询,得到“ClassID”和“StudentsID”,但它们都在同一个表中,我不知道是否只更改查询部分就能得到我需要的。所以我的桌子会是这样的:Php 如何在JSON中包含列表和对象?,php,mysql,sql,json,Php,Mysql,Sql,Json,我想让JSON知道在“ClassID”:1,“StudentsID”:[1,2,3,4]在类中没有出现,我试图做一个查询,得到“ClassID”和“StudentsID”,但它们都在同一个表中,我不知道是否只更改查询部分就能得到我需要的。所以我的桌子会是这样的: Table: School ClassID | StudentsID 1 1 1 2 2 2 2 3 2
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";
}
只需一个查询,使用
GROUP\u CONCAT
将同一班级的所有学生合并
SELECT ClassID, GROUP_CONCAT(StudentID) AS StudentsID
FROM School
GROUP BY ClassID
ORDER BY ClassID
GROUP\u CONCAT
创建一个逗号分隔的字符串,您可以在PHP中使用explode()
将其转换为数组
$list = array();
while ($row = mysqli_fetch_object($qry)) {
$list[] = array('ClassID' => $row['ClassID'], 'StudentsID' => explode(',', $row['StudentsID']);
}
echo json_encode($list);
您面临的问题是什么?请显示您尝试过的代码!如果没有什么可看的,我们无法帮助/纠正。我添加了我尝试过的代码!!!还有我得到的JSONback@dexter我一直在尝试用一个错过一节课的学生列表做一个JSON。“ClassID”将是JSON中的对象,但我必须在这个对象中列出所有错过“ClassID”的学生。但不幸的是,我在这方面是新手,我一直在努力完成这项工作。@Jeff我已经添加了您要求的代码和代码生成的JSON。你能帮我吗?除了pdo我怎么做$列表=数组();而($row=$mysqli_fetch_object($qry)){$list[]=array('ClassID'=>$row['ClassID'],'StudentsID'=>explode(',',',$row['StudentsID']);}echo json_encode($list);
mysqli_fetch_object($qry)
变成$statement->fetch。
$list = array();
while ($row = mysqli_fetch_object($qry)) {
$list[] = array('ClassID' => $row['ClassID'], 'StudentsID' => explode(',', $row['StudentsID']);
}
echo json_encode($list);