[英]How can I count a number inside a foreach?
How can I count from 2 up (until the foreach reached the end of the loop)? 我如何从2开始计数(直到foreach到达循环结束)?
Code used: 使用的代码:
for($i=0;$i<7;$i++) { //loop 7 times
$date->add(new DateInterval('P1W')); //add one week
$formatted_time = strftime("%A, %d. %B %Y, %H:%M", $date->getTimestamp());
$formatted_time_scnpart = strftime("%H:%M", $date_scn->getTimestamp());
$evenname = $event->title;
$bad_words = array('Example1','Example1','Example2','Example3','Example4','Example5');
foreach($bad_words as $bad_word){
if(in_array($eventname, $bad_words)) {
break;
} else {
// This is the modal
$ray = [2,3,4,5,6,7,8,9,10];
$cnt = 2;
echo '<span style="font-weight:400;">'.$cnt++.'. '.'Termin: '.'</span>';
echo '<span>'.$formatted_time.' - '.$formatted_time_scnpart.'</span><br/>';
break;
}
}
}
As you can see in the first echo
I already tried to count with a solution from Quora but because I am already inside a foreach, this won't work and would break the other code. 正如您在第一个echo
看到的,我已经尝试使用Quora的解决方案进行计数,但是由于我已经在foreach中,因此无法正常工作,并且会破坏其他代码。 (or at least I don't know how) (或者至少我不知道如何)
将$ cnt = 2放入循环之前,将$ cnt ++放入循环中,这样它将从2开始计数。
You need to put $cnt
outside foreach
您需要将$cnt
放在foreach
之外
like this: 像这样:
$cnt = 2;
foreach($bad_words as $bad_word){
if(in_array($eventname, $bad_words)) {
break;
} else {
echo '<span style="font-weight:400;">'.$cnt++.'. '.'Termin: '.'</span>';
echo '<span>'.$formatted_time.' - '.$formatted_time_scnpart.'</span><br/>';
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.