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 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。