【问题标题】:Array for Json Month sum of columnJson Month 列总和的数组
【发布时间】:2018-01-23 10:58:54
【问题描述】:

我现在正在为我的图表创建一个 json 文件。我想要一个类似

的输出

[{"ts":"九月","ph":23},{"ts":"七月","ph":13}]

其中 9 月的 ph 值相当于值:10、8、2、3,而 7 月的 ph 值相当于我数据库中的 10 和 3。

但现实是我只得到了这个输出

[{"ts":"九月","ph":23}]

来自下面的代码。我想添加 7 月的 ph 值。

$sumsep = 0;
$sumjul = 0;
     while($row = mysqli_fetch_array($result))
        {        
      /* Push the results in our array */
        //   $point = array("ts" =>  date('m',strtotime($row['time_stamp'])) ,"ph" =>  $row['ph']);
        $monthNum = date('m',strtotime($row['time_stamp']));
        $dateObj   = DateTime::createFromFormat('!m', $monthNum);
        $monthName = $dateObj->format('F');

        if(($monthName=="September")){
        $data_points = array();
         $sumsep += $row['ph'];
          $point = array("ts" =>  $monthName,"ph" =>  $sumsep);
        array_push($data_points,$point); 
            }

 }

请!!我需要你的帮助!!!

【问题讨论】:

  • 不要在循环中定义你的$data_points 数组,你会在每次迭代时覆盖它。为什么你的循环中有一个条件?数学应该由数据库完成:SUM() ... GROUP BY ...
  • 计算每个月的ph总和,应该在数据库端做一些查询,是的,在while循环之外定义你的$data_points
  • 感谢您的关注,我非常感谢..因为我在数组中工作,所以数据库上的 SUM() 不起作用,它必须是 $sumsep += $row['ph ']; .因为我需要总结数组

标签: php json web charts


【解决方案1】:

你可以做这样的事情。这将为您的 mysql 查询结果的每个月创建一个数组条目并将其求和。

// Init your data point by month array    
$data_points = array();
while($row = mysqli_fetch_array($result)) {        
    $monthNum = date('m',strtotime($row['time_stamp']));
    $dateObj   = DateTime::createFromFormat('!m', $monthNum);
    $monthName = $dateObj->format('F');

    // Check if already a result for this month
    if (array_key_exists($monthName, $data_points)) {
        // Sum you pH
        $data_points[$monthName]->ph += $row['ph'];
    } else {
        // Create first pH entry for month
        $data_points[$monthName] = new stdClass();
        $data_points[$monthName]->ph = $row['ph'];
        $data_points[$monthName]->ts = $monthName;
    }
}
// Extract only result (months name as key not needed)
echo json_encode(array_values($data_points));

【讨论】:

  • 锦感谢您的回复!我真的很感激。但我猜 array_key_exist() 不适用于这个..
  • 输出是这样的,array(3) { ["July"]=> array(2) { ["ts"]=> string(4) "July" ["ph" ]=> int(69) } ["August"]=> array(2) { ["ts"]=> string(6) "August" ["ph"]=> int(752) } ["September" ]=> array(2) { ["ts"]=> string(9) "September" ["ph"]=> int(13) } }
  • 需要有这样的输出 [{"ts":"September","ph":23},{"ts":"July","ph":13}]
  • 固定函数名称和数据提取,现在应该可以工作了
  • 是的,它的工作谢谢你..但是。它的工作原理是这样的:array(3){ ["July"]=> array(2) { ["ts"]=> string(4) "July" ["ph"]=> int(69) }。我只想显示月份和 ph 值的总和..像这样 [{"ts":"September","ph":23},{"ts":"July","ph":13} ]
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多