可能重复:使用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天的每一天都在数组中 .
有关如何做到这一点的任何建议?
1 回答
最有效的方法是使用
DateTime
而不是strtotime
:现在,您可以像这样形成日期数组:
这个initializes your array类似于:
现在你有一个包含过去7天所有可能日期的数组,你可以在循环中执行此操作:
您无需检查数组键是否存在,因为它确保存在 .
最后,我建议查看
DATETIME
或其他相关的日期/时间列类型,因为它们比存储UNIX时间戳更有用 . 您可以使用MySQL日期/时间函数来正确选择要查找的行,而不必在每次要根据时间查询数据时创建UNIX时间戳 .