iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 14
0
Modern Web

PHP入門系列 第 14

Day14-PHP二維陣列、多維陣列

  • 分享至 

  • xImage
  •  

二維陣列索引值有兩個,可視為兩個一維陣列。

➤$陣列命名 [索引值(列)] [索引值(行)] = 值 ;

[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"; 
?>

➤array()函式

https://ithelp.ithome.com.tw/upload/images/20190930/20120962SyvvQoRUxu.png

行列對應的概念:
https://ithelp.ithome.com.tw/upload/images/20190930/20120962Rzi06gMXkQ.png

索引可以自己命名,當索引值為數字時可省略。

範例會更清楚:
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迴圈:

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走訪所有元素。


上一篇
Day13-PHP一維陣列
下一篇
Day15-PHP函數(1)
系列文
PHP入門30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言