【问题标题】:how to get the key of an item of the array inside foreach loop in php [duplicate]如何在php中的foreach循环中获取数组项的键[重复]
【发布时间】:2016-07-27 08:06:57
【问题描述】:

下面是我拥有的数组的示例。

  Array (
[952] => Array ( [Date] => 2016-06-23 01:55:17 [SValues] => Array ( [total] => 1 [Name] => Name [OverAge] => No))
[91] => Array ( [Date] => 2016-06-23 01:55:17 [SValues] => Array ( [total] => 1  [Name] => Name [OverAge] => No))
[83] => Array ( [Date] => 2016-06-23 01:55:17 [SValues] => Array ( [total] => 1 [Name] => Name [OverAge] => No)))

然后,我将这个数组放入 foreach 循环中。

foreach($the-main-array as $item)
{
          //I want to get the key of the item here (952,91,83)
}

那么我怎样才能在循环中获取项目的键呢?

请帮助我。提前致谢。

【问题讨论】:

  • 去看看foreach()手册页

标签: php arrays foreach


【解决方案1】:

您只需要指定一个变量来存储密钥作为foreach 循环设置的一部分。你可以这样做:

foreach($the-main-array as $key => $item){
    echo "This is the key: ".$key;
}

为清楚起见,您可以随意调用$key 变量。不一定是$key


相关阅读:

【讨论】:

    【解决方案2】:

    使用这个,

    foreach($the-main-array as $key => $item)
    {
    // Put your code here.
    // $key have the key value.
    
    }
    

    【讨论】:

      【解决方案3】:
      foreach($mainArray as $k => $item){
          $k is the key
          $item is the value
      }
      

      【讨论】:

        猜你喜欢
        • 2012-06-15
        • 2017-07-08
        • 2010-09-08
        • 2019-04-29
        • 2013-07-18
        • 2019-08-28
        • 2015-05-03
        • 2012-08-05
        相关资源
        最近更新 更多