作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想要一个 JSON 来知道在“ClassID”:1中,“StudentsID”:[1,2,3,4]没有出现在类里面,我试图做一个查询给我带来了“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_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"}]}
最佳答案
通过一个查询即可完成此操作,使用 GROUP_CONCAT
将同一类(class)的所有学生组合在一起。
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);
关于php - 如何在 JSON 中包含列表和对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53891615/
我是一名优秀的程序员,十分优秀!