得到foreach循环数组的索引 [英] Get index of array in foreach loop

查看:426
本文介绍了得到foreach循环数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

 的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆