可能重复:
使用PHP创建过去30天的数组
我正在尝试创建一个"最近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 ) 
这样,即使日期没有出现在MySQL查询中,过去7天的每一天都在数组中.
有关如何做到这一点的任何建议?
最有效的方法是使用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;
}
这会将您的数组初始化为:
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时间戳.
| 归档时间: | 
 | 
| 查看次数: | 5140 次 | 
| 最近记录: |