如何使用foreach循环遍历这个php关联数组

时间:2015-11-07 17:29:05

标签: php arrays foreach

$students = array(
    'rishab' => array(
        'age' =>25 ,
        'marks' =>400,
        'class' =>'MCA'
     ), 
     'kamran' => array(
        'age' =>23 ,
        'marks' =>550,
        'class' =>'MBA'
     ),
     'Sunil'  => array(
         'age' =>23 ,
         'marks' =>550,
         'class' =>'MBA'
     )
); 

如何使用foreach循环遍历这个php关联数组?

2 个答案:

答案 0 :(得分:2)

你可以制作一个双foreach来循环所有子数组的所有值。

foreach($students as $key => $value) {
    echo 'Key: '.$key.'<br />';
    foreach($value as $s_key => $s_value) {
        echo 'Sub key: '.$s_key.' => '.$s_value.'<br />';
    }
    echo '<br />';
}

结果:

Key: rishab
Sub key: age => 25
Sub key: marks => 400
Sub key: class => MCA

Key: kamran
Sub key: age => 23
Sub key: marks => 550
Sub key: class => MBA

Key: Sunil
Sub key: age => 23
Sub key: marks => 550
Sub key: class => MBA

答案 1 :(得分:0)

foreach( $students as $name=>$student){
    print $name . ":" . $student["class"] . PHP_EOL;
}

将输出此

rishab:MCA
kamran:MBA
Sunil:MBA