假设我有一个像这样的php数组:
Array ( [0] => 2017-08-25 06:27:00 [1] => 2017-08-25 07:38:00 [2] => 2017-08-25 08:34:00 [3] => 2017-08-25 09:57:00 [4] => 2017-08-25 11:08:00 [5] => 2017-08-25 12:37:00 [6] => 2017-08-25 14:12:00 [7] => 2017-08-25 15:21:00 [8] => 2017-08-25 16:59:00 [9] => 2017-08-25 18:08:00 [10] => 2017-08-25 19:05:00 [11] => 2017-08-25 20:03:00 [12] => 2017-08-25 21:04:00 [13] => 2017-08-25 21:59:00 [14] => 2017-08-25 23:02:00 )
并且想要计算数组中每个时间戳之间的时间(以分钟为单位)。
输出应该是 数组([0] => 69 [1] => 56 [2] ....)
我不知道如何用foreach解决这个问题。
答案 0 :(得分:1)
我快速前进,只是循环查看是否有下一个值,然后减去它,除以60得到分钟:
$dates = ['2017-08-25 06:27:00', '2017-08-25 07:38:00', '2017-08-25 08:34:00', '2017-08-25 09:57:00'];
$values = [];
foreach ($dates as $index => $date) {
$date = strtotime($date);
if (!empty($dates[$index+1])) {
$nextDate = strtotime($dates[$index+1]);
$values[] = ($nextDate-$date) / 60;
}
}
var_dump($values);
答案 1 :(得分:1)
即使答案已经被接受,我仍然认为我会给出我的意见,因为我觉得还有其他选项更健壮,更清晰/更容易理解。
PHP有一组专门用于处理日期计算的本机对象,即DateTime
和DateInterval
。利用这些对象将使代码更易于阅读和理解,这反过来意味着代码更容易出错并且更易于维护。
$dateArr = ['2017-08-25 06:27:00', '2017-08-25 07:38:00', '2017-08-25 08:34:00'];
$previousDate = '';
foreach($dateArr as $dateStr) {
$curDate = new DateTime($dateStr);
if(!empty($previousDate)) {
$diff = $previousDate->diff($curDate);
echo $diff->format('%i min').PHP_EOL;
}
$previousDate = $curDate;
}
此循环将输出以下内容:
11 min
56 min
当然,如果要将此值用于计算,则需要进行一些额外的操作以将其转换为数值类型。
$min = $diff->format('%i');
if(is_numeric($min)) {
$min = (int) $min;
echo $min.' ('.gettype($min).')'.PHP_EOL;
}
else {
echo 'Oops, something went wrong :('.PHP_EOL; // good place to throw an exception, this echo is only for demo purposes
}
输出:
11 (integer)
56 (integer)
使用DateTime
对象还可以更轻松地捕获格式错误的日期,因为它会抛出异常而不是静默失败。
try {
$wrongDate = new DateTime('foobar');
echo $wrongDate->format('Y-m-d h:i:d').PHP_EOL;
}
catch(Exception $e) {
echo $e->getMessage().PHP_EOL; // the exception is caught
}
try {
$wrongToTime = strtotime('foobar');
echo $wrongToTome.PHP_EOL; // no exception si thrown and
// an undefined variable notice is thrown
}
catch(Exception $e) {
echo $e->getMessage().PHP_EOL;
}
试一试here!
答案 2 :(得分:0)