26
第第第 第第第第第 第第第 [email protected] http://www.ywdeng.idv.tw

第三章 陣列的使用 鄧姚文 [email protected]

Embed Size (px)

Citation preview

Page 1: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

第三章 陣列的使用

鄧姚文[email protected]

http://www.ywdeng.idv.tw

Page 2: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

大綱

何謂陣列 關連式陣列 陣列排序 數值索引陣列 多維陣列

Page 3: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

何謂陣列

連續資料的集合 透過索引或 key 存取

Page 4: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

數值索引陣列 $products = array(“Tires”, “Oil”, “Spark Plugs”); array() 是一個程式結構,不是函式 $products[0] 即 “ Tires” $products[1] 即 “ Oil” $products[2] 即 “ Spark Plugs” for ($i = 0; $i < 3; $i++)

echo “$products[$i]”; 可以隨時增加元素

$products[3] = “Fuses”;

Page 5: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

range

Create an array containing a range of elements

array range ( int low, int high [, int step])

Page 6: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

<?php// array(0,1,2,3,4,5,6,7,8,9)foreach(range(0, 9) as $number) { echo $number;}// The step parameter was introduced in 5.0.0// array(0,10,20,30,40,50,60,70,80,90,100)foreach(range(0, 100, 10) as $number) { echo $number;}// Use of characters introduced in 4.1.0// array('a','b','c','d','e','f','g','h','i');foreach(range('a', 'i') as $letter) { echo $letter;}// array('c','b','a');foreach(range('c', 'a') as $letter) { echo $letter;}?>

<?php// array(0,1,2,3,4,5,6,7,8,9)foreach(range(0, 9) as $number) { echo $number;}// The step parameter was introduced in 5.0.0// array(0,10,20,30,40,50,60,70,80,90,100)foreach(range(0, 100, 10) as $number) { echo $number;}// Use of characters introduced in 4.1.0// array('a','b','c','d','e','f','g','h','i');foreach(range('a', 'i') as $letter) { echo $letter;}// array('c','b','a');foreach(range('c', 'a') as $letter) { echo $letter;}?>

Page 7: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

關連式陣列

$prices = array(“Tires” => 100,“Oil” => 10, “Spark Plugs” => 4);

$prices[“Tires”] 即 100 在迴圈中使用 each() 和 list() 存取陣列元素

each : Return the current key and value pair from an array and advance the array cursor If the internal pointer for the array points past the end of the

array contents, each() returns FALSE. List : Assign variables as if they were an array

list() only works on numerical arrays and assumes the numerical indices start at 0.

Page 8: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

while ($element = each($prices)) { echo $element["key"]; echo "-"; echo $element["value"]; echo "<br>";}

while ($element = each($prices)) { echo $element["key"]; echo "-"; echo $element["value"]; echo "<br>";}

reset($prices);while (list($product, $price) = each($prices)) { echo "$product - $price <br>";}

reset($prices);while (list($product, $price) = each($prices)) { echo "$product - $price <br>";}

$prices = array("Tires"=>100,"Oil"=>10,"Spark Plugs"=>4);

$prices = array("Tires"=>100);$prices["Oil"] = 10;$prices["Spark Plugs"] = 4;

$prices = array("Tires"=>100,"Oil"=>10,"Spark Plugs"=>4);

$prices = array("Tires"=>100);$prices["Oil"] = 10;$prices["Spark Plugs"] = 4;

Page 9: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

多維陣列

$products = array(array(“TIR”, “Tires”, 100),array(“OIL”, “Oil”, 10),array(“SPK”, “Spark Plugs”, 4));

$product[0][0] 即 “ TIR”

Page 10: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

陣列排序

數值索引陣列 sort() 升冪(從小到大)排序

關連式陣列 asort()

Sort an array and maintain index association ksort()

Sort an array by key

逆向排序(降冪,從大到小) rsort() 、 arsort() 、 krsort()

Page 11: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");asort ($fruits);reset ($fruits);while (list ($key, $val) = each ($fruits)) { echo "$key = $val\n";}

This example would display:

c = appleb = bananad = lemona = orange

Page 12: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");ksort ($fruits);reset ($fruits);while (list ($key, $val) = each ($fruits)) { echo "$key = $val\n";}

This example would display:

a = orangeb = bananac = appled = lemon

Page 13: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

在多維陣列中排序

自行定義物件比較大小的方式,把多維陣列當作物件的一維陣列排序 自行定義物件比較大小的函式,傳入參數:兩個物件,傳回

值: =0 兩個物件相等 >0 第一個物件比較大 <0 第二個物件比較大

void usort ( array array, callback cmp_function) Sort an array by values using a user-defined comparison

function 逆向使用者自訂排序 kusort()

Page 14: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

function cmp ($a, $b) { if ($a == $b) return 0; return ($a > $b) ? -1 : 1;}$a = array (3, 2, 5, 6, 1);usort ($a, "cmp");while (list ($key, $value) = each ($a)) { echo "$key: $value\n";}

function cmp ($a, $b) { if ($a == $b) return 0; return ($a > $b) ? -1 : 1;}$a = array (3, 2, 5, 6, 1);usort ($a, "cmp");while (list ($key, $value) = each ($a)) { echo "$key: $value\n";}

This example would display:

0: 61: 52: 33: 24: 1

This example would display:

0: 61: 52: 33: 24: 1

Page 15: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

對陣列重新排序

shuffle() 亂排 This function shuffles (randomizes the order of the

elements in) an array. You must use srand() to seed this function.

Example: http://w3.im.knu.edu.tw/~annie/chapter03/bobs_front_page.php

Page 16: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

相反的順序

array_reverse -- Return an array with elements in reverse order array array_reverse ( array array [, bool preserve_keys])

array_reverse() takes input array and returns a new array with the order of the elements reversed, preserving the keys if preserve_keys is TRUE.

$input = array ("php", 4.0, array ("green", "red"));$result = array_reverse ($input);$result_keyed = array_reverse ($input, TRUE);

$input = array ("php", 4.0, array ("green", "red"));$result = array_reverse ($input);$result_keyed = array_reverse ($input, TRUE);

Page 17: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

This makes both $result and $result_keyed have the same elements, but note the difference between the keys. The printout of $result and $result_keyed will be:

This makes both $result and $result_keyed have the same elements, but note the difference between the keys. The printout of $result and $result_keyed will be:

Array( [0] => Array ( [0] => green [1] => red )

[1] => 4 [2] => php)Array( [2] => Array ( [0] => green [1] => red )

[1] => 4 [0] => php)

Array( [0] => Array ( [0] => green [1] => red )

[1] => 4 [2] => php)Array( [2] => Array ( [0] => green [1] => red )

[1] => 4 [0] => php)

Page 18: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

由檔案載入陣列範例: vieworders.php file -- Reads entire file into an array

array file ( string filename [, int use_include_path [, resource context]])

Identical to readfile(), except that file() returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Page 19: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

由檔案載入陣列範例: vieworders2.php explode -- Split a string by string

array explode ( string separator, string string [, int limit]) Returns an array of strings, each of which is a substring of

string formed by splitting it on boundaries formed by the string separator. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If separator is an empty string (""), explode() will return FALSE. If separator contains a value that is not contained in string, then explode() will return an array containing string.

intval -- Get integer value of a variable int intval ( mixed var [, int base])

Page 20: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

其他陣列操作

each() -- Return the current key and value pair from an array and advance the array cursor

next() -- Advance the internal array pointer of an array

prev() -- Rewind the internal array pointer current() -- Return the current element in an array end() -- Set the internal pointer of an array to its last

element reset() -- Set the internal pointer of an array to its

first element

Page 21: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

對陣列中每一個元素逐一進行運算

array_walk -- Apply a user function to every member of an array int array_walk ( array array, callback function [,

mixed userdata])

Page 22: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

<?php$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");function test_alter (&$item1, $key, $prefix) { $item1 = "$prefix: $item1";}function test_print ($item2, $key) { echo "$key. $item2<br>\n";}echo "Before ...:\n";array_walk ($fruits, 'test_print');array_walk ($fruits, 'test_alter', 'fruit');echo "... and after:\n";array_walk ($fruits, 'test_print');?>

<?php$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");function test_alter (&$item1, $key, $prefix) { $item1 = "$prefix: $item1";}function test_print ($item2, $key) { echo "$key. $item2<br>\n";}echo "Before ...:\n";array_walk ($fruits, 'test_print');array_walk ($fruits, 'test_alter', 'fruit');echo "... and after:\n";array_walk ($fruits, 'test_print');?>

Page 23: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

The printout of the program above will be:

Before ...:d. lemona. orangeb. bananac. apple... and after:d. fruit: lemona. fruit: orangeb. fruit: bananac. fruit: apple

The printout of the program above will be:

Before ...:d. lemona. orangeb. bananac. apple... and after:d. fruit: lemona. fruit: orangeb. fruit: bananac. fruit: apple

Page 24: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

計算陣列元素個數 count -- Count elements in a variable

int count ( mixed var) Returns the number of elements in var, which is typically an

array (since anything else will have one element). If var is not an array, 1 will be returned (exception:

count(NULL) equals 0). sizeof -- Alias of count() array_count_values -- Counts all the values of an

array array array_count_values ( array input) array_count_values() returns an array using the values of

the input array as keys and their frequency in input as values.

Page 25: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

將陣列轉純量變數 extract -- Import variables into the current symbol

table from an array int extract ( array var_array [, int extract_type [, string

prefix]]) This function is used to import variables from an array into

the current symbol table. It takes an associative array var_array and treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to extract_type and prefix parameters.

extract() checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table. The way invalid/numeric keys and collisions are treated is determined by the extract_type. It can be one of the following values:

Page 26: 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com

將陣列轉純量變數 EXTR_OVERWRITE ( default )

If there is a collision, overwrite the existing variable. EXTR_SKIP

If there is a collision, don't overwrite the existing variable. EXTR_PREFIX_SAME

If there is a collision, prefix the variable name with prefix. EXTR_PREFIX_ALL

Prefix all variable names with prefix. Beginning with PHP 4.0.5, this includes numeric variables as well.

EXTR_PREFIX_INVALID Only prefix invalid/numeric variable names with prefix. This flag was added in PHP 4.0.5.

EXTR_IF_EXISTS Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This

is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example. This flag was added in PHP 4.2.0.

EXTR_PREFIX_IF_EXISTS Only create prefixed variable names if the non-prefixed version of the same variable exists in the

current symbol table. This flag was added in PHP 4.2.0. EXTR_REFS

Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the var_array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the extract_type. This flag was added in PHP 4.3.0.