【问题标题】:How to get last 7 days using PHP [duplicate]如何使用 PHP 获取最后 7 天 [重复]
【发布时间】:2012-06-26 22:28:02
【问题描述】:

可能重复:
Create an Array of the Last 30 Days Using PHP

我正在尝试创建一个具有“最近 7 天销售额”的数组,即今天加上前 6 天。到目前为止我正在使用它:

$rightnow = time(); 
$time_window = $rightnow - (60*60*24*6); // 6 days ago + today = 7 days

$tw_time = date('M d', $time_window);
$tw_time = strtotime($tw_time); // 6 days ago starting at 00:00:00

$valid_sales = mysql_query("SELECT amt, created FROM sales WHERE created > $tw_time");

$sale_data = array();

foreach ($valid_sales as $sale) {

    $display_date = date('M d', $sale['created']);

    if (array_key_exists($display_date,$sale_data)) { // If date is in array

        $sale_data[$display_date] = $sale_data[$display_date] + $sale['amt']; // Add amount to date's sales

    } else { // If date is not in array

        $sale_data[$display_date] = $sale['amt']; // Create key with this amount

    }

} // End foreach valid_sales

这将给我一个数组,其中键是日期,值是该日期的销售额。即:

Array ( [Jun 19] => 19.00 [Jun 20] => 52.50 [Jun 22] => 2.00 ) 

我遇到的问题是我需要将每一天添加到数组中,即使那天没有销售(使用 MySQL 查询没有找到结果)。所以,我想得到一个这样的数组:

Array ( [Jun 19] => 19.00 [Jun 20] => 52.50 [Jun 21] => 0.00 [Jun 22] => 2.00 [Jun 23] => 0.00 [Jun 24] => 0.00 [Jun 25] => 0.00 ) 

这样,过去 7 天的每一天都在数组中,即使日期没有出现在 MySQL 查询中。

关于如何做到这一点的任何建议?

【问题讨论】:

  • 你在 mysql 数据库中使用 unixtimetamps 吗?! O_o

标签: php mysql arrays


【解决方案1】:

解决此问题的最可靠方法是使用DateTime 而不是strtotime

$now = new DateTime( "7 days ago", new DateTimeZone('America/New_York'));
$interval = new DateInterval( 'P1D'); // 1 Day interval
$period = new DatePeriod( $now, $interval, 7); // 7 Days

现在,您可以像这样形成日期数组:

$sale_data = array();
foreach( $period as $day) {
    $key = $day->format( 'M d');
    $sale_data[ $key ] = 0;
}

这个initializes your array 类似于:

array(8) {
 ["Jun 18"]=>      int(0)
  ["Jun 19"]=>      int(0)
  ["Jun 20"]=>      int(0)
  ["Jun 21"]=>      int(0)
  ["Jun 22"]=>      int(0)
  ["Jun 23"]=>      int(0)
  ["Jun 24"]=>      int(0)
  ["Jun 25"]=>      int(0)
}

现在您有一个包含过去 7 天所有可能日期的数组,您可以在循环中执行此操作:

$display_date = date('M d', $sale['created']);
$sale_data[$display_date] += $sale['amt'];

您不需要检查数组键是否存在,因为它保证存在。

最后,我建议查看 DATETIME 或其他相关的日期/时间列类型,因为它们在这里比存储 UNIX 时间戳更有用。您可以使用 MySQL 日期/时间函数来正确选择要查找的行,而不必在每次要根据时间查询数据时创建 UNIX 时间戳。

【讨论】:

  • new DateTime('7 days ago'); 也可以解决问题。
  • +1 推荐DateTime。我看到太多使用strtotime 的答案。 DateTime 是面向对象的,除非您使用 PHP
猜你喜欢
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
相关资源
最近更新 更多