PHP-计算数组循环中各行之间的日期(foreach) [英] PHP - Calculate date between rows in a array loop (foreach)
问题描述
我正在搜索如何精确地计算数组循环中的值.
i was searching how to calculate values in an array loop, a foreach preciselly.
问题是我必须计算此结果的日期之间的天数.
The problem is that i have to calculate the days between dates of this result.
示例:
<ul>
<?php
$values[] = array('example'=>'example1','date'=>'2016-25-12');
$values[] = array('example'=>'example2','date'=>'2016-26-12');
$values[] = array('example'=>'example3','date'=>'2016-28-12');
$values[] = array('example'=>'example4','date'=>'2016-30-12');
foreach($values[] as $example){
echo "<li>".$example['example']." - ".$example['date']." - ".$DAYS BETWEEN EACH DATE$."</li>";
}
?>
</ul>
要变成这样:
我该如何计算?*第一个不显示任何内容,因为它的第一个寄存器.其他的则显示实际行与最后一个(上)之间相隔了多少天.
How can i make this calc? *the first shows nothing because its the first register.. the others shows how many days passed between the actual row and the last one (above).
Ty.
推荐答案
我更改了数组中日期的格式,因为 YYYY-DD-MM
无法识别为有效格式, YYYY-MM-DD
是.
I changed the formatting of your date in the array, as YYYY-DD-MM
isn't recognized as a valid format, YYYY-MM-DD
is.
然后,只需保存以前的值并计算天数差即可.
Then it's just a matter of saving the previous value and calculating the difference in days.
<ul>
<?php
$values = array();
$values[] = array('example' => 'example1', 'date' => '2016-12-25');
$values[] = array('example' => 'example2', 'date' => '2016-12-26');
$values[] = array('example' => 'example3', 'date' => '2016-12-28');
$values[] = array('example' => 'example4', 'date' => '2016-12-30');
$previous = null; // Define the variable
foreach($values as $example){
echo "<li>".$example['example']." - ".$example['date'];
if ($previous !== null) { // If it's null, we're in the first loop
$difference= strtotime($example['date'])-strtotime($previous);
echo " - ".floor($difference/(60*60*24)); // $difference is in seconds, so convert to days by dividing by 60sec*60min*24hrs
}
$previous = $example['date']; // Set the current value, so it will be saved for the next iteration
echo "</li>";
}
?>
</ul>
上面的输出将是
- example1-2016-12-25
- example2-2016-12-26-1
- example3-2016-12-28-2
- example4-2016-12-30-2
这篇关于PHP-计算数组循环中各行之间的日期(foreach)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!