获取foreach中的索引名称

时间:2013-09-02 10:54:04

标签: php

$array = array('first' => array(1, 3), 'second' => array(5,6), 'third' => array(8,4));

foreach($array as $a){
  echo "key = " . key($a) . "\n";
};

如何从此数组中获取索引名称? 我想收到:

key = first
key = second
key = third

但这会在每种情况下返回我key = 0为什么?我怎样才能得到索引的名字?

codepad

2 个答案:

答案 0 :(得分:0)

试试这个:

foreach($array as $key => $val){
  echo "key = " . $key . "\n";
};

如果您想要打印该值:

foreach($array as $key => $val){
   echo "value = " . $val . "\n";
 };

答案 1 :(得分:0)

使用foreach的其他语法:

foreach ($array as $key => $value)
{
    echo "Key: ".$key;
}