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

时间:2021-08-18 01:32:30

In the following:

在下面的:

<?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 . " " ;
}

?>

?>

This outputs Paul Jones 31

这输出了Paul Jones 31

How can I get it to output JUST the first names fNames?

我怎样才能输出JUST名字fName?

i.e. Paul, Mike, John

即保罗,迈克,约翰

4 个解决方案

#1


5  

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

// output: Paul Mike John 

#2


2  

You probably want to iterate over the main array rather than an individual element in it.

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

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

#3


1  

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

#4


1  

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

#1


5  

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

// output: Paul Mike John 

#2


2  

You probably want to iterate over the main array rather than an individual element in it.

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

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

#3


1  

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

#4


1  

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