如何从PHP中的MySQL时间戳计数打印月份名称?

时间:2014-06-20 15:46:51

标签: php mysql

我使用json输出计算时间戳月份的文章视图。我有这段代码:

$value = array();
$stats  = Access::FETCH("SELECT COUNT(*) AS id FROM news_stats GROUP BY YEAR(date), MONTH(date)");

foreach($stats as $key => $value){

   $rows2[] = $value['id'];

   }
echo json_encode($rows2);

输出为:NOTE: this is count for month each month

["1","6"]

我需要为此输出打印月份名称:

["january","June"]

如何打印月份名称? Menaig是:1 , 6从哪个月算起?

3 个答案:

答案 0 :(得分:4)

您可以通过调整查询来在MySQL本身中执行此操作,以便使用MONTHNAME

SELECT COUNT(*) AS id FROM news_stats GROUP BY YEAR(date), MONTHNAME(date);

通过mktime / date组合在PHP中执行此操作的唯一真正价值在于,您的脚本需要数值以及完整月份名称本身。但这也可以通过像SELECT YEAR(date) as year, MONTH(date) as month, MONTHNAME(date) as month_name…这样的东西来解决,但这完全取决于编码需求。

另外,刚刚意识到它在您的示例中都为GROUP BY编码。所以也许这会更好:

SELECT COUNT(*) AS id,
YEAR(date) as `year`,
MONTH(date) as `month`,
MONTHNAME(date) as `month_name`,
FROM `news_stats`
GROUP BY `year`, `month`;

答案 1 :(得分:2)

试试这个:

$value = array();
$stats = Access::FETCH("SELECT id, YEAR(FROM_UNIXTIME(date)) AS `YEAR`, 
                MONTHNAME(FROM_UNIXTIME(date)) AS `MONTH`, 
                COUNT(*) AS id 
         FROM news_stats GROUP BY `YEAR`, `MONTH` ORDER BY `YEAR` DESC, `MONTH`");


foreach($stats as $key => $value){

   $rows2[] = $value['MONTH'];

   }
   echo json_encode($rows2);

输出是:

["June","August"]

享受!!

答案 2 :(得分:1)

您可以在foreach循环中使用与此类似的代码:

<?php
$monthNum = $value['id'];
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
?>

来自:http://gilbert.pellegrom.me/php-month-number-to-month-name-the-easy-way/