通过MySQL迭代时间戳

时间:2017-12-08 10:26:02

标签: php mysql unix-timestamp

所以,这应该是一个简单的。我有一个JS图表需要数组,如下所示:

var seriesData = [
   [13.58, 14.99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  //this is the totals in month order
   [0, 0, 17.32, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    //lines are repeated per category in table
]; 

mysql表中的数据看起来像这样:

----------------------------------------------
| t_id |    t_date    | t_total | t_category |   //very simplified 
|   1  |  1483257600  |  13.58  |    C1      |   //there are a lot more categories
|   2  |  1485936000  |  14.99  |    C1      |   //but this gives the idea
|   3  |  1488355200  |  17.32  |    C2      |   //dates will be random
----------------------------------------------

我需要什么

最终结果应该在表格中的每个类别中打印出一个新元素,其中SUM类别总计按月顺序(当前年份)。

这就是我用SQL得到的(是的不是很好),但是我从这里开始就被困住了。

mysqli_query($mysqli,"select sum(t_total), FROM_UNIXTIME(t_date, '%Y') AS year from table 
where FROM_UNIXTIME(t_date, '%Y') = year(curdate()) group by t_category");

那些PHP / SQL boffin可以给我一些方向吗?

全部谢谢

1 个答案:

答案 0 :(得分:0)

右。花了一点时间在这上面,我得到了解决方案:

我意识到这是一个具体案例,但万一其他人正在寻找这个,那么这可能有所帮助。

var seriesData = [
<?
$gc = mysqli_query($mysqli,"select distinct `t_category` from `table` where `t_user` = '1' and `t_status`='$tstatus' order by `t_category` asc ")or die(mysqli_error($mysqli));
  if(mysqli_num_rows($gc) > 0){
    while($gcr = mysqli_fetch_assoc($gc)){
      $categ = $gcr["t_category"];
      $start = $month = strtotime('first day of january this year');
      $end = time();
      $gsmarr = [];
        while($month < $end){
          $mnmb = new DateTime("@$month");
          $mn = $mnmb->format('n');
          $gs = mysqli_query($mysqli,"select sum(`t_total`) as `grspc` from `table` where `t_user`='1' and `t_category`='$categ' and `t_status`='$tstatus' and month(from_unixtime(`t_date`)) = '$mn' ")or die(mysqli_error($mysqli));
             while($gsr = mysqli_fetch_assoc($gs)){
               if($gsr["grspc"] == ""){
                  array_push($gsmarr,'0');
               }else{
                  array_push($gsmarr,$gsr["grspc"]);
               }
             }
          $month = strtotime("+1 month", $month);
      }
    $impmnt = implode(',',$gsmarr);
    echo "[".$impmnt."],";
   }
  }else{
     echo "oops";
  }
?>
];