![]() |
溫瑞烘老師的教學歷程檔案(Teaching ePortfolio) - 102-1--物件導向程式設計 - 第5週講義-PHP陣列 |
| 第5週講義-PHP陣列PHP陣列 陣列是一種特殊的形態,是可以儲存很多值的變數。在PHP中,用array()可以建立一個陣列。例如:$a=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六"); $a就是陣列。 $a[0]="星期日"、$a[1]="星期一"、$a[2]="星期二"、$a[3]="星期三"...,整個$a[0]="星期日"稱之為陣列元素。 其中0、1、2、3、4為「索引」。"星期日"、"星期一"、"星期二"、"星期三".等為「陣列值」。 上例我們沒有指定索引,所以,PHP會自動給個正整數即0、1、2、3、4...等作為索引。 也可以這樣設定陣列:$a=array(0=>"星期日","星期一","星期二","星期三","星期四","星期五","星期六"); 也可以這樣: $a[]="星期日"; $a[]="星期一"; $a[]="星期二"; $a[]="星期三"; $a[]="星期四"; $a[]="星期五"; $a[]="星期六"; 前述的例子都是以索引0開始。
如此,$country[1]="台灣",$country[5]="美國",$country[8]="日本"...,那$country[4]呢?$country[15]呢?查無此值或無定義。 我們也可以用文字來作為索引,例如: $country=array("tw"=>"台灣","us"=>"美國","jp"=>"日本","cn"=>"中國"); 如此,$country['tw']="台灣",$country['us']="美國",$country['jp']="日本"...依此類推。 迴圈讀取陣列 <?php $country=array("tw"=>"台灣","us"=>"美國","jp"=>"日本","cn"=>"中國"); echo "Value: $value "; } ?> 結果Value: 台灣 Value: 美國 Value: 日本 Value: 中國 <?php $country=array("tw"=>"台灣","us"=>"美國","jp"=>"日本","cn"=>"中國"); foreach ($country as $key => $value) { echo "Key: $key, Value: $value"; } ?> 結果Key: tw, Value: 台灣Key: us, Value: 美國Key: jp, Value: 日本Key: cn, Value: 中國 <?php $country=array("台灣","美國","日本","中國"); $cnt = count($country); for ($i=0; $i<$cnt; $i++) { echo($country[$i]); } ?> 結果 台灣美國日本中國 再或者 <?php $country=array("tw"=>"台灣","us"=>"美國","jp"=>"日本","cn"=>"中國"); reset($country); while (list($key, $value) = each($country)) { echo "Key: $key, Value: $value"; } ?> 結果Key: tw, Value: 台灣Key: us, Value: 美國Key: jp, Value: 日本Key: cn, Value: 中國 練習 1. 寫一個函數 function assign($first,$step,$cnt)設定陣列資料$cnt個回傳 2. 寫一個函數 function output($array) 輸出陣列資料
<?php $array=assign(10,5,8); output($array); function assign($first,$step,$cnt) { function output($array) { ?> 4. 加入函數function sum($array) 回傳加總之和 5. 加入函數function even($array) 回傳偶數加總之和 if($num & 1) { // 最後一位元與 1 做 bit and 運算 6. 加入函數function odd($array) 回傳奇數加總之和 7. 加入函數function add__value($array,$value) 回傳每個位置加上$value 以下列順序呼叫完成程式 $array=assign(10,5,8); 再以$array=assign(1,3,10); 產生 1 4 7 10 ----
|
|
中華科技大學數位化學習歷程 - 意見反應 | ![]() |