Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用PHP获取最后7天_Php_Mysql_Arrays - Fatal编程技术网

如何使用PHP获取最后7天

如何使用PHP获取最后7天,php,mysql,arrays,Php,Mysql,Arrays,可能重复: 我正在尝试创建一个包含“最近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

可能重复:

我正在尝试创建一个包含“最近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查询中


有什么建议吗?

最有效的方法是使用
DateTime
而不是
strotime

$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;
}
这一点类似于:

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时间戳。

您是否在MySQL数据库中使用unixtimetamps?!O_O
newdatetime('7天前')
也会起作用。+1用于推荐
DateTime
。我用
strotime
看到了太多的答案。DateTime是面向对象的,除非您使用的是PHP<5.2.0,否则再使用旧的日期/时间函数就没有意义了。依我拙见