[PHP_Day 4]_基本語法part4_Array、HashTable


陣列(可以不只侷限一種型態,可以是Object)
陣列的初始化有兩種寫一種是透過array小括號
一種則是直接一組方括號
可以用print_r來輸出整個array索引對應成員


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
 
 $arrStr = array("apple","banana","cherry","桃子","葡萄柚");
 var_dump($arrStr);//陣列中string各自大小(Byte),一個中文字佔3Byte。
 echo "<br/>";
 print_r($arrStr);
 echo "<br/>";
 echo $arrStr[3];
 echo "<br/>";
 
 $arrStr2 = ["a1","a2","a3"];
 var_dump($arrStr2);
 echo "<br/>";
 print_r($arrStr2);
 echo "<br/>";
 echo $arrStr2[1];
 echo "<br/>";
 
 $arrInt = [15,68,77,98];
 var_dump($arrInt);
 echo "<br/>";
 print_r($arrInt);
 echo "<br/>";
 
 $arrFloat = [9.8,5.4,3.1,6.24];
 var_dump($arrFloat);
 echo "<br/>";
 print_r($arrFloat);
 echo "<br/>";
 
 $arrMultiType = [9.8,7,"apple"];
 var_dump($arrMultiType);
 echo "<br/>";
 print_r($arrMultiType);
 echo "<br/>";
?>




在PHP中Array跟HashTable(有點像C#的Dictionary->Key-Val)是用
同一方式在定義(同一件事情)
只是寫法有別於Array額外擴充跟改寫
預設會自動分配index從0開始的Key
事實上也可自定義客制化Key識別(但盡量不要型態參差不一致)
要用客制化Key就統一都字串不要穿插int或float


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
 
 $arr1 = array(
  1 => "banana",
  0 => "apple"
 );
 print_r($arr1);
 /*
 //預設都是index從0開始(換成HashTable則是Key依序0,1)
 $arr1 = array(
  0 => "apple",
  1 => "banana"
 );
 */
 
 echo "<br/>";
  
 $arr2 = array(
  "fruit2" => "banana",
  "fruit1" => "apple"
 );
 print_r($arr2);
 echo "<br/>";
 echo $arr2["fruit2"];
?>


Array的新增及刪除異動


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
 
 $arr1 = array(
  "apple",
  "banana"
 );
 print_r($arr1);
 echo "<br/>";
 
 //新增(從尾端)
 array_push($arr1,"cake");
 array_push($arr1,"date");
 print_r($arr1);
 echo "<br/>";
 
 //刪除(從尾端)
 array_pop($arr1);
 print_r($arr1);
 echo "<br/>";
 //Array ( [0] => apple [1] => banana [2] => cake )
 
 
 //於特定index位置之後穿插(類似將兩個array合併在一塊)
 //參數3代表是否要取代掉原本的(0:不要)
            //Array ( [0] => apple [1] => banana [2] => cake )
 //array_splice($arr1,1,0,["pink"]);//Array ( [0] => apple [1] => pink [2] => banana [3] => cake )
 array_splice($arr1,1,1,["pink"]);  //Array ( [0] => apple [1] => pink [2] => cake )
 print_r($arr1);
 echo "<br/>";
 
 //刪除特定index的元素(不會重新調整index)--->寫的時候容易導致無法確切得知元素位置
 //Array ( [0] => apple [1] => pink [2] => cake )
 //Array ( [0] => apple [2] => cake )
 unset($arr1[1]);//delete [1] => pink
 print_r($arr1);
 echo "<br/>";
 
 //array 轉 json string
 $arr2 = array(
  "apple",
  "banana",
  "cake"
 );
 echo json_encode($arr2);
 echo "<br/>";
 echo json_encode($arr1);
 
 
?>


留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題