我试图使用MySQL/ PHP创建这种JSON对象。
[
{
"hours":0
"vulnerability":867
"file":166
"virus":59
},
{
"hours":1
"vulnerability":400
"file":14
"virus":40
},
]我试图减少发送到服务器的查询量,因为我的数据库规模相当大。我的查询返回以下结果:

因此,在遍历数据的同时,我得到了这样的JSON返回:
{
"hours":0
"vulnerability":867
},
{
"hours":0
"file":14
},
{
"hours":0
"virus":59
},
]我希望在不使用foreach循环中使用多个SQL查询的情况下创建所需的输出。以下是完整代码-
$query = "SELECT hour(generated_time) as hours, subtype, count(subtype) as y from description group by subtype, hours order by hours asc, y desc";
$result = mysql_query($query) or die(mysql_error());
$output = array();
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data["time"] => $row['hours'];
$data[$row['subtype']] => $row['y'];
array_push($output, $data);
}
echo json_encode($output);发布于 2014-04-04 18:56:03
只需运行一次SQL查询,然后遍历结果,并将每一行放在正确的位置。
就像这样:
$output = array();
while ($row = mysql_fetch_assoc($result)) {
$key = intval($row['hours']);
if(!isset($output[$key])){
$output[$key] = array('hours' => $key);
}
$output[$key][$row['subtype']] = intval($row['y']);
}
echo json_encode($output);发布于 2014-04-04 19:00:40
如果提前了解所有的子类型,则可以重写查询以按所需的方式格式化数据:
SELECT
hour(generated_time) as hours,
SUM(subtype = "vulnerability") AS vulnerability,
SUM(subtype = "file") AS file,
SUM(subtype = "virus") AS virus
FROM
description
GROUP BY hours 发布于 2014-04-04 18:59:48
它只是一个mySQL查询。它被放入关联数组中,循环没有调用更多的mySQL查询,而是查看循环中关联数组中的条目。
https://stackoverflow.com/questions/22870819
复制相似问题