2015-11-07 220 views
-2
$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關聯數組循環?如何通過使用foreach循環通過這個php關聯數組循環

回答

1

你可以做一個雙的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 
+0

謝謝主席先生!爲即時回覆。 – Abid

+0

我很高興我幫助你。如果答案適合您,請考慮將其標記爲接受的答案。 –

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

將輸出這個

rishab:MCA 
kamran:MBA 
Sunil:MBA