PHP-计算数组循环中各行之间的日期(foreach) [英] PHP - Calculate date between rows in a array loop (foreach)

查看:85
本文介绍了PHP-计算数组循环中各行之间的日期(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>

要变成这样:

  • example1-2016-25-12
  • example1-2016-26-12-1天
  • example1-2016-28-12-2天
  • example1-2016-30-12-2天
  • 我该如何计算?*第一个不显示任何内容,因为它的第一个寄存器.其他的则显示实际行与最后一个(上)之间相隔了多少天.

    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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆