php - 如何正确设置 PHP while 循环而不重复重复数据
问题描述
我查看了无数以前的问题,找不到与我遇到的问题相同的问题。我有一个工作脚本可以从数据库中获取我需要的数据。
<?php
$result = $conn->query("SELECT COUNT(colUser) AS userCount, colMonth as userMonth, colYear as userYear FROM MyTable GROUP BY userYear");
$newData = array();
$years = array();
$cnt = array();
while($selected_row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($years,$selected_row['userMonth']);
$tmp_key = $selected_row['userYear'];
array_push($cnt,$selected_row['userCount']);
$newData[$tmp_key] = array(
implode(',',$cnt)
);
}
$jsonResult = json_encode($newData);
echo $jsonResult;
我需要的输出是
{
"2018": ["292,181,1868,1074,2726,2213,2616,3269,1744,2839,1983,1689"],
"2019": ["2179,2027,1948,2071,2323,1963,2721,4065,4626,4660,3783,3170"],
"2020": ["4308,3307,6143,6795,1881"]
}
我得到的输出是
{
"2018": ["292,181,1868,1074,2726,2213,2616,3269,1744,2839,1983,1689"],
"2019": ["292,181,1868,1074,2726,2213,2616,3269,1744,2839,1983,1689,2179,2027,1948,2071,2323,1963,2721,4065,4626,4660,3783,3170"],
"2020": ["292,181,1868,1074,2726,2213,2616,3269,1744,2839,1983,1689,2179,2027,1948,2071,2323,1963,2721,4065,4626,4660,3783,3170,4308,3307,6143,6795,1881"]
}
此外,如果可能的话,更理想的输出将是(用零填充空月)
{
"2018": ["292,181,1868,1074,2726,2213,2616,3269,1744,2839,1983,1689"],
"2019": ["2179,2027,1948,2071,2323,1963,2721,4065,4626,4660,3783,3170"],
"2020": ["4308,3307,6143,6795,1881,0,0,0,0,0,0,0"]
}
我真诚地感谢您的帮助!
解决方案
在 GrumpyCrouton 的指导下,我能够实现我想要的结果。
$result = $conn->query("SELECT COUNT(colUser) AS userCount, colMonth as userMonth, colYear as userYear FROM MyTable GROUP BY userYear");
$newData = array();
$years = array();
$cnt = array();
while($selected_row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($years,$selected_row['userMonth']);
$tmp_key = $selected_row['userYear'];
$newData[$tmp_key][] = $selected_row['userCount'];
}
$jsonResult = json_encode($newData);
echo $jsonResult;
推荐阅读
- python - 使用 Tensorflow 数据集加载方法对 Mnist 数据集进行拆分和切片
- python - 如何在 msys2 中安装 docx2pdf python 模块(mingw - windows 64 位)
- csv - Daff csv diff 库用户定义的密钥不起作用
- reactjs - 带有参数的反应路由器链接不重定向
- latex - 使用 \includepdf 时未定义的控制序列
- debezium - 如何删除 debezium 连接器
- javascript - 如何将 pouchdb 0000003.log 文件复制到 Ionic 5 并检索数据?
- javascript - 在二维数组的每个子数组中查找最大数?Javascript
- r - glm() 误差对比只能应用于具有 2 个或更多级别的因子
- azure - 基于“错误”的 Azure 自动化警报