使用foreach循环访问多维数组的元素

时间:2012-04-17 22:50:04

标签: php arrays multidimensional-array

以下内容:

<?php
$test = array(
    array("fName" => "Paul", "lName" => "Jones", "Age" => "31"),
    array("fName" => "Mike", "lName" => "Hunt", "Age" => "3"),
    array("fName" => "John", "lName" => "Doe", "Age" => "32")
);
?>

<pre> <?php var_dump($test) ?> </pre>

<?php
foreach($test[0] as $key => $value) {
    echo $value . " " ;
}

&GT;

这会输出Paul Jones 31

如何输出JUST名字fNames

即。 Paul, Mike, John

4 个答案:

答案 0 :(得分:5)

foreach($test as $person) {
    echo $person['fName'] . " " ;
}

// output: Paul Mike John 

答案 1 :(得分:2)

您可能希望迭代主数组而不是其中的单个元素。

foreach($test as $item) {
    echo $item['fName'];
}

答案 2 :(得分:1)

foreach($test as $value) {
  echo $value['fName'] . ", " ;
}

答案 3 :(得分:1)

foreach ($test as $arr)
    echo $arr['fName'] . ', ';