如何遍历此数组数组?

时间:2020-11-08 18:51:28

标签: php

我想获得这三种动物的所有名字,那就是梅德尔,费利克斯和丹佛。这些数据最初来自mysql数据库,我正在创建一个函数来显示所有动物的名字。

var_dump($ tab)

array (size=3)
  0 => 
    array (size=8)
      'id' => string '1' (length=1)
      0 => string '1' (length=1)
      'name' => string 'Médor' (length=6)
      1 => string 'Médor' (length=6)
      'species' => string 'chien' (length=5)
      2 => string 'chien' (length=5)
      'age' => string '4' (length=1)
      3 => string '4' (length=1)
  1 => 
    array (size=8)
      'id' => string '2' (length=1)
      0 => string '2' (length=1)
      'name' => string 'Félix' (length=6)
      1 => string 'Félix' (length=6)
      'species' => string 'chat' (length=4)
      2 => string 'chat' (length=4)
      'age' => string '97' (length=2)
      3 => string '97' (length=2)
  2 => 
    array (size=8)
      'id' => string '3' (length=1)
      0 => string '3' (length=1)
      'name' => string 'Denver' (length=6)
      1 => string 'Denver' (length=6)
      'species' => string 'dinosaure' (length=9)
      2 => string 'dinosaure' (length=9)
      'age' => string '65000000' (length=8)
      3 => string '65000000' (length=8)

我尝试了这个,但是它以第一个数组而不是第二个数组的索引开头

foreach($tab as $k => $val){
$tab[$k]["name"];
}
                }

1 个答案:

答案 0 :(得分:0)

按如下所示使用foreach()循环来引用所需的元素($arr是源数组):

foreach($arr as $key => $value) {
    echo 'id : ' . $value['id'];
    echo '<br />';
    echo 'name: ' . $value['name'];
    echo '<br />';
}

输出:

id : 1
name: Médor
id : 2
name: Félix
id : 3
name: Denver

工作demo