php time string array - 删除特定时期的值

时间:2011-10-19 12:08:29

标签: php arrays

[0] => 12:00:00
[1] => 12:15:00
[2] => 12:30:00
[3] => 12:45:00
[5] => 13:15:00
[6] => 13:30:00
[7] => 13:45:00
[8] => 14:00:00
[9] => 14:15:00
[10] => 14:30:00

当我的开始时间为“ 12:30:00 ”且结束时间为“ 14:00:00 ”时,如何从上面的数组中删除值?应删除的值为 12:30:00,12:45:00,13:15:00,13:45:00和14:00:00

3 个答案:

答案 0 :(得分:1)

对于PHP> = 5.2.0,我会这样做:

$time_array = array('0' => '11:00:00',
                    '1' => '12:00:00',
                    '2' => '13:00:00',
                    '3' => '14:00:00',
                    '4' => '15:00:00',
                    '5' => '16:00:00');

echo "\nBefore:\n";
print_r($time_array);

$start = new DateTime('12:30:00');
$end   = new DateTime('14:00:00');

// Magic starts here
foreach ($time_array as $key => $value) {
  $datetime = new DateTime($value);
  if ($datetime >= $start and $datetime <= $end)
    unset($time_array[$key]);
}
// Magic finished

echo "\nAfter:\n";
print_r($time_array);

Yes, it works.

答案 1 :(得分:1)

如果您不需要保留索引

,则可以使用此方法
  error_reporting(E_ALL);
  $array = array(
    0 => '12:00:00',
    1 => '12:15:00',
    2 => '12:30:00',
    3 => '12:45:00',
    5 => '13:15:00',
    6 => '13:30:00',
    7 => '13:45:00',
    8 => '14:00:00',
    9 => '14:15:00',
    10 => '14:30:00',
  );

  $from = '12:30:00';
  $to   = '14:00:00';
  $filtered = array();
    foreach($array as $key => $value) {
  if ($value < $from || $value > $to) {
          $filtered[] = $value;
 }
  }

  var_dump($filtered);

答案 2 :(得分:0)

    $var_arr = array();
    $time_arr = array('12:00:00','12:15:00','12:30:00','12:45:00','13:15:00',
'13:30:00','13:45:00','14:00:00','14:15:00','14:30:00'); 
    $start = strtotime('12:30:00');
    $end = strtotime('14:00:00');
    foreach($time_arr as $arr):
    if(strtotime($arr)<$start || strtotime($arr)>$end):
    $var_arr[] = $arr;
    endif;
    endforeach;
    print_r($var_arr);