dongmo2324 2016-07-16 08:57
浏览 113
已采纳

在MySQL中计算年份等于日期的行数 - JSON

Am trying to come up with a JSON result showing

`[{"Year":"2014-07","Numb":4},{"Year":"2015-07","Numb":12},{"Year":"2016-07","Numb":56}]`

"Numb" equals the number of rows that the year appears. So the example above would be 4 rows where 2014 appears, 12 rows where 2015 appears and 56 rows where 2016 appears.

From there, the data is being placed into a Morris Chart. EG Number of clients who joined in YYYY. (Months are just used for the X Axis on the Morris Chart).

Am currently working with

$query = "SELECT * FROM signup ORDER BY DateAdded ASC LIMIT 0, 24";
$result = mysqli_query($mysqli,$query);

$total_rows =  $result->num_rows; // Show ALL rows regardless of date. Used in Array below

$array = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
    $date = $row['DateAdded'];
    $time=strtotime($date);
    $year=date("Y-m",$time);
    array_push($array,array('Year'=>$year,'Numb'=>$total_rows));

}

echo json_encode($array);

Currently works OK in the Morris Chart except of course the number of rows are all the same.

Seems a fairly complex query that is out of my league.

I have researched the use of COUNT, but cannot see how it handles multiple queries within one query...

  • 写回答

2条回答 默认 最新

  • duanlei8119 2016-07-16 09:14
    关注

    I dont have the mysql table so i can not test it... Please test it and tell me if it works for you...

    $query = "SELECT * FROM signup ORDER BY DateAdded ASC LIMIT 0, 24";
    $result = mysqli_query($mysqli,$query);
    
    $total_rows =  $result->num_rows; // Show ALL rows regardless of date. Used in Array below
    
    $array = array();
    
    function in_array_r($needle, $haystack, $strict = false) {
        foreach ($haystack as $key=>$item) {
            if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
                return $key;
            }
        }
    
        return false;
    }
    
    while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
    {
        $year    =  date("Y-m",strtotime($row['DateAdded']));
        $key = in_array_r($year, $array);
        if($key !== false):
             $array[$key]["Numb"] += 1;
        else:
            $array[] = array("Year"=>$year,"Numb"=>1);
        endif;
    }
    
    echo json_encode($array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误