Advanced Arrays 進階陣列

Advanced Arrays 進階陣列

Review of Arrays 陣列複習


Arrays are a useful way to store multiple values, like numbers, strings, and even other arrays: 陣列非常適用於儲存多筆的資料,像是數字.字串,甚至是其他陣列:


    $myArray = array(1, 2, 3);

Here we create an array of three numbers. Remember that array positions start from 0; therefore to access the third item in this array, we type: 這裡我們創造了一個擁有三個數字的陣列。記得陣列的初始值從0開始;因此如果想要取得陣列的第三個元素,我們輸入:


    $myArray[2];

Instructions 操作指引

On line 8, set $fruits equal to an array of three strings: 'bananas', 'apples' and 'pears'. 在第8行,建立一個包含三個字串: 'bananas', 'apples' 和 'pears'的陣列,並存入 $fruits變數裏頭。

Modify the echo statement on line 9 to display the fruit in the middle of the array (that is, it should echo "apples". 修改第9行的echo指令列用以顯示$fruits中間第二個元素(換言之,印出"apples")。


Associative Arrays 關聯式陣列


Arrays are a useful way to store multiple values, like numbers, strings, and even other arrays: 陣列非常適用於儲存多筆的資料,像是數字.字串,甚至是其他陣列:

An associative array makes use of (key => value) pairs. Some languages may separate arrays from associative arrays, but PHP treats both as the same. 一個關聯式陣列使用 key => value(名值對)。有一些程式語言認為關聯式陣列不算是一種陣列,但是PHP則將兩種視為相同。

In the editor, you will see I have declared two variables as arrays. Have a look at the first array and see if you can guess what item those values may refer to? 在編輯器,你將看到我宣告兩個變數作為陣列。看看第一個陣列然後想看看你能否看出這些元素的值所代表的是?

Now have a look at the array below it. This is an associative array. It's defined as an array like the first one, but see how I have specified keys for each of the values? 現在再看看下面的另一個陣列。這是一個關聯式陣列。它作為一個陣列被定義就和上面一樣,但是看到我是如何透過key來對應這些元素值了嗎?

Both arrays contain the same values, but in the associative array, we can access the value using a specified "key". 這兩個陣列包含了相同的值,但在關聯式陣列,我們能夠透過一個特定的"key"來取得元素值。


Instructions 操作指引

Make sense? Click Save & Submit Code when you think you've got it! 理解了嗎? 按下 Save & Submit Code當你覺得自己懂了!


Using Arrays as Maps 使用關聯式陣列(又稱Maps)

You can think of an associative array (also called a map) as being the same as a normal array, but instead of using an integer to refer to the value, you use a defined key. 你可以把關聯式陣列(又被稱為map)想成是一般的陣列,但是不透過數字來取得元素而是透過特定的 key值。

While numeric indices may be fine for looping through an array and listing all of the values, what if we need to change a certain value from an array? 數字索引值或許對於遍歷整個陣列並印出所有值很好用,但是假如你想要變動某個元素值時就變得有些麻煩。(舉例,你想要變動廠牌資料,這個值的索引值是多少? 是3還是4,就要去背很不直覺)


Instructions 操作指引

For each array in the editor, add the value "BMW" to the end of the array. For the associative array, use "make" as the key. You can add a key just as shown in the editor: 在編輯區的每一個陣列,在陣列的最後加上一個"BMW"這樣的值。如果是關聯式陣列,則使用"make"作為鍵值。你可以加上一個新的鍵就如同編輯器下方那樣:


    'key' => value

(You'll see a PHP error until you add the missing array elements.) (你將會持續的看到PHP錯誤,直到你補上缺失的陣列元素為止)


Accessing Associative Arrays 取用關聯式陣列


When accessing the values from either type of array, the only difference is whether you use an integer, or a specified key: 如要取用陣列的元素,與先前的陣列相比,唯一的差異點是之前你透過元素索引值(也就是元素的位置),而現在則是透過鍵值:


echo $car[1];
// prints 2012

echo $assocCar['year'];
// prints 2012

This exercise will demonstrate how useful specified keys in an array can be. 這些實作足以示範為何透過鍵值取值是如何比起透過索引值來的更為直覺。


Instructions 操作指引

Using the arrays from the previous exercises, write an echo statement on line 22 to talk about your car (beyond the fact that it's blue). Try using both arrays to describe the car. Which one makes it easier? 使用先前練習的這些陣列,在第22行分別透過echo指令來說明你的車子顏色,試著透過兩種不同的陣列來取得"blue"這個值。哪一個更為直覺好用勒?


Iterating Over Associative Arrays 針對關聯式陣列進行遞迴的作法

Looping through an associative array is just as easy as looping through a normal array, but you obtain the value from a specified key, not an integer. Just like in the previous exercises! 要在關聯式資料庫逐一取得每一個元素就跟透過迴圈從一般陣列取出每個元素一樣的簡單,但你是透過某個鍵值來取得值,而非索引值。這點在上一個章節就提過了!

If we only need to loop through the values of an array, we can use for. Have a look at the editor to see an example of this being used. 如果我們只需要從陣列中逐一取出這些值,一點不難。看看編輯區的這個例子來看看它們是怎麼做到的。

Remember, when using a for loop, calculate the length of the array first! 記得,當我們使用一般的陣列,務必先計算陣列的長度!

Then have a look at the foreach loop to see how we can get the key and value of each pair in the array. 接著看看如何透過foreach迴圈來逐一從陣列裡頭取出每一對鍵和值


Instructions 操作指引

In the editor, create your own associative array and loop through the keys and values. 在編輯器,自己建立一個關聯式陣列,並透過迴圈來取出每一個鍵和值。

Multidimensional Arrays 多維陣列

Not only can you store integers and strings in arrays, you can also store... other arrays! This is called a multidimensional array. 你不只可以存整數或者是字串到陣列裡頭,事實上,你還可以存入其他陣列!這樣的陣列又被稱為多維陣列。

How do we do this? Well, just like a normal array with comma-separated values, but you would put comma-separated arrays instead—just like the code in the editor. 那我們該怎麼做勒?不難,就像是在一般陣列裡頭我們用逗號來分開值,現在你改用逗號來分開陣列-就像編輯器的程式碼那樣。

$deck is an array which contains 3 rows, each being a playing card. Within each row, it has the name of the card, along with the value. $deck 是一個包含3行的陣列,每一個都是一張撲克牌的資料。換言之,在每一行裡頭,保存了撲克牌的名稱以及它的值。

To retrieve a card, we would first get the row for that card, then get the value we require (either to display the card, or calculate the player's total). 要取得一張卡,我們需要先取得那張卡的行,然後接著才能取得我們所需要的值(不管你是想要顯示這張卡片,或者是計換該玩家所擁有的所有點數)

If we access $deck[2], we would get the third row (remember, arrays start from 0 in PHP!) 如果我們取卡堆的第三(索引值為2)張,我們將會得到第三列的資料(記得,PHP的陣列索引值都是從0開始的)

That will return another array containing 2 values: the first (0) which is a string that has the value "7 of Diamonds", and the second (1) which is an integer that has the value 7. 那將會傳會另一個包含兩個值的陣列:第一個元素為字串內容為"7 of Diamonds",接著第二個元素是一個整數,其值為7

If we want the "7 of Diamonds" string, we would simply use $deck[2][0];. 假如我們想要取得"7 of Diamonds"這個字串,我們只需要使用$deck[2][0]即可

Simple! 是不是很簡單啊!


Instructions 操作指引


Try adding another card to the array. It can have whatever rank, suit, and value you like, but keep in mind the value should be a number! 試著在陣列裡頭加入另外的卡片。他可以是任何你想要的等級.花色又或是值,但請記得它的值必須為數字!

Putting it All Together 把所學的放在一起使用


This is the time to practice everything you've learned so far about associative arrays. Here's some quick reminders: 現在是讓你練習所有你所學到的關聯式陣列知識的時候了。這裡有一些快速提醒:

Arrays in PHP are zero-based (this means the numeric ID of the first value in the array will always be 0, not 1). 陣列在PHP是零基的(這意味著陣列的第一個位置永遠從0算起而非是人類習慣的1)

An array can contain values ("val1", "val2", etc… ) 一個陣列可以包含多個值(像是"val1","val2",等等,還別忘了用逗號隔開)

As an associative array, it can contain keys and values ("key1" => "val1", "key2" => "val2", etc… ) 一個關聯式陣列,他能夠包含鍵與值 ("key1" => "val1", "key2" => "val2", 等等… )

A multidimensional array can contain arrays within arrays! 所謂的多維陣列你只要理解成陣列可以被放進陣列,變成一個元素即可!

To loop through an array containing values only, you can use the for loop. For an array containing keys and values, you can use the foreach loop. 如果要逐一的取出一般陣列的值,你可以使用for迴圈。但如果是要逐一取出關聯式陣列的鍵值,你應該使用foreach迴圈比較好。


Instructions 操作指引


1.Create a variable called $myArray and set it equal to a new array that you create, which can contain any items you like. 宣告一個變數名為$myArray,然後賦值一個新的陣列給這個變數,裡頭的元素可以是任何你喜歡的東西。

2.Grab a value from your array and display it. 從你的陣列中取出某個值並且顯示它。

3.Now loop through the array and output the contents to the browser! 現在透過迴圈遍歷陣列的每一個值,並將結果輸出在結果畫面上!

PHP
分享這篇文章:

發佈自 林品爵

林品爵
一個堅信程式教育能夠改變下一代未來的狂熱者,青少年揚帆計畫的推動者。十年以上全端程式開發,上百場程式教學經驗,累積學生數達百人以上。 成大學士畢業,使用過J2EE.PHP.MySQL.CoronaSDK.Android.Objective-C.Swift.Python等技術知識,歷任友訊科技總部Java工程師首席.黑快馬股份有限公司研發經理.諾亞數碼娛樂執行長等職位,現任哥布林程式教育學苑創辦人,所開發過專案涵括產品管理系統.POS系統.拍賣平台.擴增實境.問券.社區App等等。 程式啟蒙班講師 . Laravel網頁程式班講師 . App程式班講師

關聯文章:

留下留言