如何在php中获取foreach循环中数组项的键

时间:2016-07-27 08:06:58

标签: php arrays foreach

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

  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)
}

那么如何在循环中获取项目的键?

请帮帮我。提前谢谢。

3 个答案:

答案 0 :(得分:2)

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

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

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

相关阅读:

答案 1 :(得分:0)

使用此,

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

}

答案 2 :(得分:-1)

foreach($mainArray as $k => $item){
    $k is the key
    $item is the value
}