use*_*334 448 php foreach loops
有可能找到foreach索引吗?
在一个for循环如下:
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
Run Code Online (Sandbox Code Playgroud)
$i 会给你索引.
我是否必须使用for循环或是否有某种方法来获取foreach循环中的索引?
Owe*_*wen 832
foreach($array as $key=>$value) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
$key是每个$array元素的索引
Con*_*oyP 161
你可以放入一个黑客攻击foreach,例如每次运行时增加的字段,这正是for循环在数字索引数组中提供的.这样的字段将是需要手动管理(增量等)的伪索引.
A foreach会以您的$key价值形式为您提供索引,因此不需要这样的黑客攻击.
例如,在 foreach
$index = 0;
foreach($data as $key=>$val) {
// Use $key as an index, or...
// ... manage the index this way..
echo "Index is $index\n";
$index++;
}
Run Code Online (Sandbox Code Playgroud)
Zor*_*che 19
欧文有一个很好的答案.如果您只想要密钥,并且您正在使用数组,这可能也很有用.
foreach(array_keys($array) as $key) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
小智 9
我用的++$key是而不是$key++从1开始。通常它是从0开始。
@foreach ($quiz->questions as $key => $question)
<h2> Question: {{++$key}}</h2>
<p>{{$question->question}}</p>
@endforeach
Run Code Online (Sandbox Code Playgroud)
输出:
Question: 1
......
Question:2
.....
.
.
.
Run Code Online (Sandbox Code Playgroud)
小智 8
这两个循环是等效的(当然是安全栏杆):
for ($i=0; $i<count($things); $i++) { ... }
foreach ($things as $i=>$thing) { ... }
Run Code Online (Sandbox Code Playgroud)
例如
for ($i=0; $i<count($things); $i++) {
echo "Thing ".$i." is ".$things[$i];
}
foreach ($things as $i=>$thing) {
echo "Thing ".$i." is ".$thing;
}
Run Code Online (Sandbox Code Playgroud)
我认为最好的选择是一样的:
foreach ($lists as $key=>$value) {
echo $key+1;
}
Run Code Online (Sandbox Code Playgroud)
这很容易而且通常
乔纳森是对的。PHP 数组充当映射表,将键映射到值。在某些情况下,如果定义了数组,则可以获得索引,例如
$var = array(2,5);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
Run Code Online (Sandbox Code Playgroud)
你的输出将是
2
5
Run Code Online (Sandbox Code Playgroud)
在这种情况下,数组中的每个元素都有一个已知的索引,但是如果您执行以下操作
$var = array_push($var,10);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
Run Code Online (Sandbox Code Playgroud)
你没有输出。发生这种情况是因为 PHP 中的数组不是像大多数语言中那样的线性结构。它们更像是哈希表,可能有也可能没有所有存储值的键。因此 foreach 不使用索引来抓取它们,因为如果定义了数组,它们只有一个索引。如果需要索引,请确保在遍历数组之前已完全定义数组,并使用 for 循环。
小智 5
PHP数组有内部指针,所以试试这个:
foreach($array as $key => $value){
$index = current($array);
}
Run Code Online (Sandbox Code Playgroud)
对我来说没问题(虽然只是经过初步测试).