【发布时间】:2016-02-17 12:30:19
【问题描述】:
我正在为教师制作一个显示学生考试成绩的页面。
要显示图表,我想使用Highcharts JavaScript 库。
到目前为止,我有一个 PHP 脚本,它使用 PDO 创建 JSON 数据,以后可以从不同的页面将其提供给 Highcharts。
我的问题:
如何将来自同一 student 的所有数据分组到一个数组中?请参阅最后一个示例了解我希望实现的目标。另外:我希望将所有数据包含在一个总体 JSON 数组中。
我想要这个:
[{
"student": "Andreas",
"level" : [4, 3]
}, {
"student": "Eivind",
"level" : [4, 5]
}, {
"student": "Ole",
"level" : [4, 3]
}]
这是我的 PHP 的样子:
<?php
require("config.inc.php");
$school = $_GET["school"];
$class = $_GET["class"];
//initial query
$query = 'SELECT student, taskid, level FROM task
WHERE school=' . '"' . $school . '"' . ' AND class=' . '"' . $class . '" ORDER BY student';
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["student"] = $row["student"];
$post["level"] = $row["level"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response, JSON_NUMERIC_CHECK);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
这是我从 PHP 中得到的:
{
"posts": [
{
"student": "Andreas",
"level": 4
},
{
"student": "Andreas",
"level": 3
},
{
"student": "Eivind",
"level": 4
},
{
"student": "Eivind",
"level": 5
},
{
"student": "Ole",
"level": 4
},
{
"student": "Ole",
"level": 3
}
]
}
【问题讨论】:
标签: php mysql json pdo highcharts