是否有可能找到foreach索引?
在for循环中如下所示:
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
$i会给你索引。
我必须使用for循环还是有一些方法在foreach循环中获得索引?
是否有可能找到foreach索引?
在for循环中如下所示:
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
$i会给你索引。
我必须使用for循环还是有一些方法在foreach循环中获得索引?
当前回答
这两个循环是等价的(当然除了安全栏杆):
for ($i=0; $i<count($things); $i++) { ... }
foreach ($things as $i=>$thing) { ... }
eg
for ($i=0; $i<count($things); $i++) {
echo "Thing ".$i." is ".$things[$i];
}
foreach ($things as $i=>$thing) {
echo "Thing ".$i." is ".$thing;
}
其他回答
我使用++$key而不是$key++从1开始。通常从0开始。
@foreach ($quiz->questions as $key => $question)
<h2> Question: {{++$key}}</h2>
<p>{{$question->question}}</p>
@endforeach
输出:
Question: 1
......
Question:2
.....
.
.
.
foreach(array_keys($array) as $key) {
// do stuff
}
这两个循环是等价的(当然除了安全栏杆):
for ($i=0; $i<count($things); $i++) { ... }
foreach ($things as $i=>$thing) { ... }
eg
for ($i=0; $i<count($things); $i++) {
echo "Thing ".$i." is ".$things[$i];
}
foreach ($things as $i=>$thing) {
echo "Thing ".$i." is ".$thing;
}
我认为最好的选择是这样的:
foreach ($lists as $key=>$value) {
echo $key+1;
}
这很简单,也很正常
你可以在循环外创建$i,并在循环底部执行$i++。