得到foreach循环数组的索引 [英] Get index of array in foreach loop
问题描述
考虑:
的foreach($行作为$行){
回声$行['身份证'];
回声$行['姓名'];
回声$行['姓氏'];
}
我如何获得 $行目前指数
任何给定的迭代中,无需单独计数变量
我的尝试:
的foreach($行作为$关键=> $行){
回声$行['身份证'];
回声$行['姓名'];
回声$行['姓氏'];
}
编辑下面
但 $键
给我 $行
的当前索引,而不是目前的指数 $行
。
我想要做的是:
的foreach($行作为$行){
如果(CURRENT_INDEX($行)== 0){
// 做一点事
}
回声$行['身份证'];
回声$行['姓名'];
回声$行['姓氏'];
}
据我所知,PHP不具有 CURRENT_INDEX()
函数或类似的东西。
下面就是 $行
如下:
阵列
(
[0] =>排列
(
[ID] => 1
[名字] =>名字1
[姓氏] =>姓氏1
) [1] =>排列
(
[ID] => 2
[名字] =>名字2
[姓氏] =>姓氏2
) [2] =>排列
(
[ID] => 3
[名字] =>名字3
[姓氏] =>姓氏3
)
)
您引用的数组的值作为一个数组。这就是为什么它是给你的 $行['身份证']
您需要使用 $键
因为这是在 $行
数组当前的指数值。
当您使用的foreach($行作为$关键=> $行)
这是它实际上是这样做的:
-
$行
- 通过输入数组循环 -
$键
- 第一维数组中的当前位置的键 -
$行
- 第一维数组在当前位置值
Given:
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
How do I get the current index of $rows
during any given iteration, without a separate count variable?
What I tried:
foreach ($rows as $key => $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
EDIT BELOW
But $key
gives me the current index of $row
, not the current index of $rows
.
What I want to do is:
foreach ($rows as $row) {
if(current_index($rows) == 0){
// do something
}
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
To my knowledge, PHP doesn't have a current_index()
function or something like it.
Here's what $rows
looks like:
Array
(
[0] => Array
(
[id] => 1
[firstname] => Firstname one
[lastname] => Lastname one
)
[1] => Array
(
[id] => 2
[firstname] => Firstname two
[lastname] => Lastname two
)
[2] => Array
(
[id] => 3
[firstname] => Firstname three
[lastname] => Lastname three
)
)
You are referencing the array value as an array. That's why it is giving you $row['id']
You need to use $key
as that is the value of your current index in the $rows
array.
When you use foreach($rows as $key => $row)
this is what it is practically doing:
$rows
- input array to loop through$key
- key of your current location in the first dimensional array$row
- value of your current location in the first dimensional array
这篇关于得到foreach循环数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!