dongqian5569 2016-12-27 17:20
浏览 92
已采纳

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.

Example:

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

To become something like this:

example1 - 2016-25-12 example1 - 2016-26-12 - 1 day(s) example1 - 2016-28-12 - 2 day(s) example1 - 2016-30-12 - 2 day(s)

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.

  • 写回答

4条回答 默认 最新

  • dongluanan7163 2016-12-27 17:32
    关注

    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>
    

    Output of the above would be

    • example1 - 2016-12-25
    • example2 - 2016-12-26 - 1
    • example3 - 2016-12-28 - 2
    • example4 - 2016-12-30 - 2

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀