3

I count article view by timestamp month using json output. I have this code :

$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);

output is : NOTE: this is count for month each month

["1","6"]

I need to print month name for this ouput like this:

["january","June"]

How do can in print month name ? Menaig is: 1 , 6 count from which month?

1

3 Answers 3

4

You can do it in MySQL itself by adjusting your query like so to use MONTHNAME:

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

The only real value of doing it in PHP via an mktime/datecombo is somehow your script needs the numerical value as well as the full month name itself. But that too could be addressed in MySQL by doing something like a SELECT YEAR(date) as year, MONTH(date) as month, MONTHNAME(date) as month_name… but it all depends on coding needs more than anything.

Also, just realized it’s all coded for GROUP BY in your example. So perhaps this would work better:

SELECT COUNT(*) AS id,
YEAR(date) as `year`,
MONTH(date) as `month`,
MONTHNAME(date) as `month_name`,
FROM `news_stats`
GROUP BY `year`, `month`;
Sign up to request clarification or add additional context in comments.

2 Comments

This still won't give him the monthname in his result set.
@JakeGould: jake i have a question: can list all month of the year and count by month, for each month print count if any month not have count show 0 like this : ["12","0","0","120","70","30","20","11","0","0","10","89"] how do create this?
3

Try This :

$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);

Output is :

["June","August"]

Enjoy!!

Comments

1

You can use code similar to this in the foreach loop:

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

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

1 Comment

The fundamental problem is with the query not returning any data about the month at all. No amount of PHP date manipulation will solve that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.