0

需要帮助才能获得如下结果我已经尝试了很多但无法成功。计算日期出现的次数并显示在数组中。[[Date.UTC(2011,9,23),1],[Date.UTC(2011,9,24),2],[Date.UTC(2011,9,25),5]]。

到目前为止,我能够将日期提取为数组格式,下面是我的结果。[[“03-09-2011”],[“06-09-2011”],[“06-09-2011”]]。如何添加另一行以显示每个日期和日期 Date.UTC 的计数?

请帮忙

我的代码

$mysql_connect = mysql_connect($db_host, $db_user, $db_pword, $db_name);
$query = "SELECT DATE_FORMAT(`timestamp`,'%d-%m-%Y') as date from mytable";
if (!$mysql_connect)  die("unable to connect to database: " . mysql_error());

@mysql_select_db($db_name) or die( "Unable to select database");

$result = mysql_query($query);
$response = array();
$stats = array();
while($row=mysql_fetch_array($result))
{ 
    $date = $row ['date'];

    $stats[] = array ($date);

} 

$Response[] = $stats;

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($Response));
fclose($fp);


//die ("Failed to execute Query: " . mysql_error());

mysql_close($mysql_connect);
4

1 回答 1

0

You can get the dates already counted out of the database with a GROUP BY clause:

SELECT 
    DATE_FORMAT(`timestamp`,'%d-%m-%Y') as date, 
    COUNT(*) as frequency
FROM mytable 
GROUP BY DATE_FORMAT(`timestamp`,'%d-%m-%Y')

Conversion from a date string to timestamp (as Javascript's Date.UTC does) can either be done in PHP or MySQL. UNIX_TIMESTAMP(CAST(timestamp AS DATE)) will get you the timestamp for date straight out of the database.

In PHP http://php.net/manual/en/function.strtotime.php can be used to get a unix timestamp from the format you are already retrieving: $date_utc = strtotime($row['date']); For more control use DateTime http://php.net/manual/en/book.datetime.php (strtotime can't be configured - it just uses standard assumptions).

$date_time = DateTime::createFromFormat('d-m-Y', $row['date']);
$date_utc = $date_time->getTimestamp();
于 2013-09-04T19:50:27.643 回答