我的数组在foreach中返回数组

时间:2014-05-13 11:15:28

标签: php

有人可以解释我为什么无法从该阵列获取数据? 我的回声只返回“数组”。哪里出错了?

<?php
$people = array( 
array("name"=>"Bob","age"=>8,"colour"=>"red"), 
array("name"=>"Greg","age"=>12,"colour"=>"blue"), 
array("name"=>"Andy","age"=>5,"colour"=>"purple")); 


foreach($people as $vperson => $person){ 

    echo $person;

} 
?>

3 个答案:

答案 0 :(得分:2)

当你说你有一个数组时,你的变量$ person也是一个数组,因此你不能对它做出回应。您可以通过名称&#34;年龄,名称和颜色&#34;来访问值。

试试这个:

<?php
$people = array( 
array("name"=>"Bob","age"=>8,"colour"=>"red"), 
array("name"=>"Greg","age"=>12,"colour"=>"blue"), 
array("name"=>"Andy","age"=>5,"colour"=>"purple")); 


foreach($people as $vperson => $person){ 

    echo $name = $person['name'];
    echo $age = $person['age'];
    echo $colour = $person['colour'];
    echo "<br>";

} 
?>

答案 1 :(得分:0)

因为您的打印数组为echo

您可以打印数组:

    <?php
    $people = array( 
    array("name"=>"Bob","age"=>8,"colour"=>"red"), 
    array("name"=>"Greg","age"=>12,"colour"=>"blue"), 
    array("name"=>"Andy","age"=>5,"colour"=>"purple")); 
    foreach($people as $vperson => $person){ 
    echo '<pre>';
        print_r($person);
    echo '</pre>';


echo $name = $person['name'];
    echo $age = $person['age'];
    echo $colour = $person['colour'];
    } 

答案 2 :(得分:0)

使用此按钮显示键和等效值

foreach($people as $pe)
{
  foreach($pe as $key => $person) 
  {
     echo $key.' : '.$person.' </br> ';
  }
}