PDO Mysql查询格式化javascript的输出

时间:2018-03-19 15:44:55

标签: mysql

这对我来说是一个真正令人头疼的问题:/ 我有一个包含来自三个不同区域的报告的表格,我需要能够将数据拉出并以条形图形式显示,该条形图由每周每个区域找到的行分隔。在将键盘敲打键盘3天之后,我承认失败并转向你这些优秀的人。我最接近的是4次查询数据库和逐步遍历数组以尝试构建输出。

表:

|  id  |  region  |  date        |
|   1  |   West   |  2018-01-06  |
|   2  |   East   |  2018-01-12  |
|   3  |  Midwest |  2018-02-03  |
|   4  |  East    |  2018-02-06  |
|   5  |  West    |  2018-02-16  |

等。  我需要将数据格式化为:

{ y: 'weekofyear', west: (rowsfound), east: (rowsfound), midwest: (rowsfound) },
{ y: 'weekofyear', west: (rowsfound),  east: (rowsfound), midwest: (rowsfound) },
{ y: 'weekofyear', west: (rowsfound),  east: (rowsfound), midwest: (rowsfound) },
{ y: 'weekofyear', west: (rowsfound),  east: (rowsfound), midwest: (rowsfound) }

1 个答案:

答案 0 :(得分:-1)

我使用了数据透视表:

$stmt = $pdo->prepare("
SELECT
WEEK(date) as week,
COUNT(IF(region = 'east', id, NULL)) AS east,
COUNT(IF(region = 'west', id, NULL)) AS west,
COUNT(IF(region = 'midwest', id, NULL)) AS midwest
FROM
table 
GROUP BY
WEEK(date);
");

$stmt->execute();
foreach ($stmt as $row) {
$allweeks[] = $row;
}

$json = json_encode($allweeks); 
print $json;