【问题标题】:Count how many events were each month计算每个月有多少事件
【发布时间】:2016-02-26 22:56:28
【问题描述】:

我有一个图表,我想在其中填写有关我每个月有多少记录的信息。图表需要接收这种格式的数据:

    data: [
    ["Jan", 140],
    ["Feb", 240],
    ["Mar", 190],
    ["Apr", 140],
    ["May", 180],
    ["Jun", 320],
    ["Jul", 270],
    ["Aug", 180]
],

我需要生成每个月有多少记录。我的数据库看起来像:

id |   start     |    end     |
------------------------------
1  |  2015-10-01 | 2015-10-31 |
2  |  2015-10-05 | 2015-10-09 |
3  |  2015-10-06 | 2015-10-07 |
4  |  2015-11-01 | 2015-11-02 |
5  |  2015-11-03 | 2015-11-06 |
6  |  2015-11-09 | 2015-10-13 |
7  |  2015-11-16 | 2015-10-18 |
8  |  2015-11-21 | 2015-10-29 |

所以我们在 10 月有 3 条记录,在 11 月有 5 条记录。 我应该如何正确初始化一个函数,最终将返回我可以传递给数据的正确外观格式? 我可以获取像

这样的记录

型号:

   function specialtest($start, $end) {
   $q = ("SELECT count(*) as count FROM reservations WHERE end > '$start' and start < '$end'");
   $query = $this->db->query($q);
   print json_encode($query->result_array());
   exit;
}

然后在Controller中:

   $data = $this->model->specialtest($arg, $arg2);

但这并不是我所需要的。我每个月都需要这些记录而不调用任何函数参数,因为我不知道它们?有什么想法吗?

【问题讨论】:

  • 用sql语句或者view取数据,用php展示
  • @Ilan Hasanov : 你想要一个 sql 查询来检索你想要的数据吗?
  • 在将count 附加为列后,您是否尝试使用group by month。
  • i need those records each month without calling any function arguments as i don't know them - 好一个:D

标签: php mysql json codeigniter


【解决方案1】:

希望对你有帮助……

function specialtest() {
$data = [];
$year = 2015;

for ($i=1; $i<=12; $i++){
    $sql = 'SELECT count(*) as count FROM reservations WHERE YEAR(start) = '.$year.' AND MONTH(start)='.$i;
    $query =  $this->$db->query($sql);
    $results = $query->result_array();
    $data[] = [date('M', strtotime($year.'-'.$i.'-01')) => $results[0]['count']];
}

echo json_encode($data);
exit(); 
}

【讨论】:

  • 这太完美了!你能补充一些解释吗?它是如何工作的,$results[0] 似乎也有点不清楚
  • $year 中的每个月执行 sql,然后以月份名称为键将计数结果添加到数据数组中。我写了 $results[0]['count'] 因为我不知道您用于活动记录的内容,所以我假设 $query->result_array() 将结果作为数组返回,因此获取 count 列的 sql 结果应该为 $ results[0]['count'] 并且我使用了 $results[0] 因为查询应该只返回 1 行计数。
  • 这在明年不会起作用,它总是会从 2015 年开始。
  • @Adunahay lol... function specialtest($year)... or $year = date('Y');任何人都可以使这甚至是 php 的初学者......就像第 1.0.1 课一样
【解决方案2】:

只要该功能没有在应用程序的其他地方使用,就将查询更新为如下所示:

$q = "SELECT DATE_FORMAT(start, '%b') as month, DATE_FORMAT(start, '%Y') as year, count(*) as count FROM reservations WHERE end > '$start' and start < '$end' GROUP BY DATE_FORMAT(start, '%b-%Y')";

请注意,您需要包含年份,这样明年您就不会抓取上一年的条目。

【讨论】:

  • 我应该如何使用$start,$end?作为 2015:2015 年?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
相关资源
最近更新 更多