数组for循环语法

时间:2011-04-11 16:06:30

标签: php

如果我有:

$data = array(
  'id01' => array(
    'firstName' => 'Eric',
    'lastName' => 'Smith',
  ),
  'id02' => array(
    'firstName' => 'John',
    'lastName' => 'Turner',
  ),
);

foreach ( $data as $key){
    print "$key[firstName]<br>";
    echo $key[0];
}

$key[0]部分无效...基本上我正在尝试输出id01,然后是id02,基本上是forloop正在处理的数组的id部分......

关于正确语法的任何想法?

4 个答案:

答案 0 :(得分:5)

您需要的是

foreach ($data as $key => $val){
    print "$val[firstName]<br>"; //changed to $val
    echo $key; //prints id01, id02
}

答案 1 :(得分:1)

0没有关键字,只有名字和姓氏 - 你需要这样做

foreach ($data as $key => $value)
{
    echo "Key is " . $key . ", value of firstName 
          is " . $value["firstName"] . "<br />";
}

答案 2 :(得分:1)

这样的事情?

foreach ( $data as $key=>$value){
    print "$value[firstName]<br>";
    echo $key.'<br />';
}

答案 3 :(得分:0)

尝试:

foreach ( $data as $key=>$value)