首页 > 解决方案 > 如何正确设置 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"]
}

我真诚地感谢您的帮助!

标签: phparraysjsonwhile-loop

解决方案


在 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;

推荐阅读