[0][0] | [0][1] |[0][2]
[1][0] | [1][1] |[0][2]
[2][0] | [2][1] |[2][2]
一一給予位置對應的值:
<?php
$classmate[0][0]="Alicia";
$classmate[1][0]="Balo";
$classmate[2][0]="Cindy";
?>
行列對應的概念:
索引可以自己命名,當索引值為數字時可省略。
範例會更清楚:
1.
<?php
$grade = array("Student_Alicia"=>array("Math"=>40,"English"=>100),
"Student_Balo"=>array("Math"=>100,"English"=>80),
"Student_cindy"=>array("Math"=>80,"English"=>70));
?>
<?php
$Student_Alicia = array("Math"=>40,"English"=>100);
$Student_Balo = array("Math"=>100,"English"=>80);
$Student_cindy = array("Math"=>80,"English"=>70);
$grade = array($Student_Alicia,$Student_Balo,$Student_cindy);
?>
foreach(陣列 as 變數){ echo 變數; }
<?php
$classmate = array("Alicia","Balo","Cindy");
foreach($classmate as $name){
echo $name."</br>";
}
?>
輸出:
Alicia
Balo
Cindy
foreach(陣列 as索引變數 => 變數){ echo 變數; echo 索引變數; }
<?php
$classmate = array("girlfriend"=>"Alicia",
"bestfreind"=>"Balo",
"classleader"=>"Cindy");
foreach($classmate as $position => $name ){
echo " my ".$position." is ".$name."</br>";
}
?>
輸出:
my girlfriend is Alicia
my bestfreind is Balo
my classleader is Cindy
印出二維陣列元素:雙層迴圈
<?php
$grade = array(0=>array("Math"=>40,"English"=>100),
1=>array("Math"=>100,"English"=>80),
2=>array("Math"=>80,"English"=>70));
for($i = 0;$i<count($grade);$i++){
foreach($grade[$i] as $subject => $score){
echo $subject." score:".$score."</br>";
}
}
?>
輸出:
Math score:40
English score:100
Math score:100
English score:80
Math score:80
English score:70
先使用for迴圈,再使用foreach走訪所有元素。