[英]PHP how to skip first element in while loop
我有获取两个时间之间的时间的功能,我想要这样的代码打印
数组([0] => 07:00:00 [1] => 08:00:00 [2] => 09:00:00 [3] => 10:00:00 [4] => 11:00 :00)
(第一个元素未打印/添加)
下面的代码是这样打印的。
数组([0] => 06:00:00 [1] => 07:00:00 [2] => 08:00:00 [3] => 09:00:00 [4] => 10:00 :00 [5] => 11:00:00)
编码
$si="06:00 AM";
$sb="11:00 AM";
$st= date ( 'H:i:s', strtotime ($si) );
$en=date( 'H:i:s', strtotime ($sb ) );
$NoOfHours = $this->getTimesfromRange(date('H:i:s', strtotime($st)),date('H:i:s',strtotime($sb)));
print_r($NoOfHours);
功能获取时间
public function getTimesfromRange($start, $end){
$dates = array($start);
while(end($dates) < $end){
if(date('H:i:s', strtotime(end($dates).' +1 hour'))==$start){
continue;
}else{
$dates[] = date('H:i:s', strtotime(end($dates).' +1 hour'));
}
}
return $dates;
}
问题:如何不打印while循环中的第一个元素,我尝试使用continue但不能正常工作。
array_shift()函数从数组中删除第一个元素,并返回已删除元素的值。 您可以按以下方式更改功能以工作。 您可以在这里找到更多详细信息
public function getTimesfromRange($start, $end){
$dates = array($start);
while(end($dates) < $end){
$dates[] = date('H:i:s', strtotime(end($dates).' +1 hour'));
}
array_shift($dates);
return $dates;
}
只需更改此代码$dates = array($start);
到$dates = [];
不会将$ start存储到您的数组中。 并且您必须像这样修改您的功能, Live demo 。
function getTimesfromRange($start, $end){
$dates = [];
while(end($dates) < $end){
$date = end($dates) != FALSE ? end($dates) : $start;
$dates[] = date('H:i:s', strtotime($date.' +1 hour'));
}
return $dates;
}
您还可以使用以下方法从结果数组中删除第一个元素
array_shift($result);
或未unset($result[0]);
或array_slice($result, 1);
。 这些不建议。
如果我理解您的问题,则可以在数组中获得正确的日期,但您希望打印除元素0以外的所有内容。
就我个人而言,我只是将其复制并删除元素0。
$NoOfHours = $this->getTimesfromRange(date('H:i:s', strtotime($st)),date('H:i:s',strtotime($sb)));
$printable = $NoOfHours;
unset($printable[0]);
var_dump($printable);
假定它是您不希望使用计数器$i;
的任何时间显示的第一个值$i;
public function getTimesfromRange($start, $end){
$dates = array($start);
$i = 0;
while(end($dates) < $end){
if($i != 0){
$dates[] = date('H:i:s', strtotime(end($dates).' +1 hour'));
}
$i++;
}
return $dates;
}
For循环排除[0]
public function getTimesfromRange($start, $end){
$dates = array($start);
For($i=0; $i<count($dates)); $i++){
If($i != 0){
$dates[] = date('H:i:s', strtotime(end($dates).' +1 hour'));
}
}
return $dates;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.