首页 > 解决方案 > 如何循环使用条件

问题描述

这是我的 $update 数组

Array
(
[0] => 08:31:08
[1] => 08:32:08
[2] => 08:33:08
[3] => 10:34:08
[4] => 08:51:08
[5] => 08:21:08
[6] => 10:39:08
[7] => 08:41:08
[8] => 08:49:08
[9] => 08:20:08
[10] => 08:11:08
[11] => 10:50:08
)

这是我的代码

$default_computed = 9:30:00
$timin ="";

  for ($x=0; $x < count($update) ; $x++) { 

      if (strtotime($update[$x]) > strtotime($default_computed) ) {

            $timin .= $update[$x].',';
            $replace_timin = substr_replace($timin ,"",-1);
            $updated_timin = explode(",",$replace_timin);
            $late_time_in = count($updated_timin);

            echo "<pre>";
            print_r($update);
            print_r($timin);
            die();
  }
}

我想要这个输出,但它已经停止了 1 次

10:34:08,10:39:08,10:50:08,

我怎样才能连续循环以获得我的目标输出?

标签: php

解决方案


我假设您的脚本试图找出数组中的哪个时间超出了截止时间(即$default_computed = 9:30:00)。

考虑到这一点,我建议您对这个问题采取不同的方法,避免字符串操作(使用substr_replaceexplode)并开始使用DateTime类:

$default_computed = '9:30:00'; // cutoff time
$cutoff = new DateTime($default_computed); // using DateTime
foreach ($update as $time) { // so each time element inside the array
    $time_in = new DateTime($time); // load each time
    if ($time_in >= $cutoff) { // if this time is beyond the cutoff
        echo $time_in->format('H:i:s'); // output it
    }
}

它们使用起来更容易和直接,因为您只需及时加载,并且可以直接在条件下DateTime与对象进行比较。DateTimeif

time in因此,与时间相比,它基本上是数组内部的每个cutoff


推荐阅读