對於網頁程式設計來說,最重要的就是存取和讀寫資料了。儲存方式可能有很多種,可以是字串、陣列、檔案的形式等
今天學習了數組,可以說是PHP的資料應用中較重要的一種方式。 PHP的陣列函數眾多,下面是我學習的小結,藉此記之,便於以後鑑之…
一、數組定義:
數組的定義使用array()方式定義,可以定義空數組:
複製程式碼 程式碼如下:
$number = array(1,3 ,5,7,9);
//定義空數組
$result = array();
$color =array("red","blue","green");
//自訂鍵值
$language = (1=>"English",3=>"Chinese",5=>"Franch");
//定義二維陣列
$two = array(
"color"=>array("red","blue"), //用逗號結尾
"week"=>array("Monday","Friday") / /最後一句沒有標點
);
?>
#二、建立陣列:
建立陣列包含的函數有compact( )、
1.compact()函數-將一個或多個變數(包含陣列)轉換為陣列:
array compact (#mixed $varname [, mixed $... ] ) array compact (#mixed $varname [, mixed $... ] )
程式碼如下:
$number = "1,3,5,7,9"; 相反的函數是extract()作用顧名思義就是將數組轉換為單一的字串,鍵值作為其字串名稱,數組值作為字串的值。
運行結果:
程式碼如下:
Array ( [number] => 1,3,5,7 ,9 [string] => I'm PHPer [array] => Array ( [0] => And [1] => You? ) ) array array_combine ( array $keys , array $values )
程式碼如下:
$number = array("1","3","5","7","9"); 運行結果:
Array ( [1] => I [3] => Am [5] => A [7] => PHP [9] => er )
3.range()函數-建立指定範圍的陣列:
不多說了,直接上實例—
程式碼如下:
#$ array1 = range(0,100,10);//0為起始值,100為結束值,10為步進值(預設步進值為1). 運行結果:
程式碼如下: 複製程式碼 程式碼如下:
Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 [6] => 60 [7] => 70 [9] => 90 [10] => 100 )
陣列( [0] => A [1 ] => B [2] => D [4] => E [6 ] => H [8] => I [9] => K [11] => M [13] => O [15] = > P[16] => Q[18] => S[20] = > V[22] ; W [23] => X [24] => Y [25] => Z )
Array ( [0] => z [1] => y [2] => x [ 3] => v [6] => s [8] => q [ 10]=>o[12]=>n[14]=>l[16]=>j[17] ] => h [19 ] => g [21] => e [23] => c [24] => b [25] => a )
4.array_fill()函數-填充陣列函數:
#$array = range(1,10);
$fillarray = range("a","d");
$arrayFilled = array_fill(0,5,$fillarray);//這裡的$fillarray可以是字串,如"test".
echo ""; <br>print_r ($arrayFilled); <br>echo "
";
$keys = array("字串","2",9,"SDK","PK");
$array2 = array_fill_keys($keys,"測試");
echo ""; <br>print_r ($array2); <br>echo "
";
?
執行結果:
複製程式碼 程式碼如下:
Array
(
[0] => 陣列
(
[0] => a
[1] => b
[2] => c
[3] = > d
)
[1] => 陣列
(
[0] => a
[1] => b
[2] => c
[3] => d
)
[2] => 陣列
(
[0] => a
[1] => b
[2] => c
[3 ] => d
)
[3] => 陣列
(
[0] => a
[1] => b
[2] => c
[3] => d
)
[4] => 陣列
(
[0 ] => a
[1] => b
[2] => c
[3] => d
)
陣列
(
[string] => 測試
[2] => 測試
[9] => 測試
[SDK] => 測試
[PK] => test
)
#二、 吞吐的遍歷:
##1.foreach 遍歷:
##foreach (array_expression as $value){}
##複製程式碼如下:
$speed = array(50,120,180,240,380);
foreach($speed as $keys=>$values){
echo $keys."=>".$values."
";
}
?
執行結果:
複製程式碼
# 程式碼如下:
#0=>50
1=>120
2=>180
3=>240
4=>380
2.while 迴圈遍歷:
# while 迴圈遍歷一般結合清單函數,以下是實例
# 複製程式碼
程式碼如下:
##< ?PHP ##$ Staff = array(
array("姓名","性別","年齡"),
array("小張","男",24),
array("小王","女",25),
array("小李","男",23)
);
echo "<表格邊框=2>";
while(list($keys,$value) = every($staff)){
list($name,$sex,$age) = $value;
echo "
#名稱 | ||
##小張 | ||
24 | 小王 | |
25 | 小李 |
3.for迴圈遍歷:
複製程式碼 程式碼如下:
$speed = range( 0,220,20);
for($i =0;$i
}
? >
運行結果:
複製程式碼 程式碼如下:
0 20 40 60 80 100 120 140 160 180 200 220
以上是PHP數組相關講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!