1 / 26

第三章 陣列的使用

第三章 陣列的使用. 鄧姚文 joseph.deng@gmail.com http://www.ywdeng.idv.tw. 大綱. 何謂陣列 關連式陣列 陣列排序 數值索引陣列 多維陣列. 何謂陣列. 連續資料的集合 透過索引或 key 存取. 數值索引陣列. $products = array( " Tires " , " Oil " , " Spark Plugs " ); array() 是一個程式結構,不是函式 $products[0] 即 " Tires " $products[1] 即 " Oil "

kaelem
Download Presentation

第三章 陣列的使用

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 第三章 陣列的使用 鄧姚文 joseph.deng@gmail.com http://www.ywdeng.idv.tw

  2. 大綱 • 何謂陣列 • 關連式陣列 • 陣列排序 • 數值索引陣列 • 多維陣列

  3. 何謂陣列 • 連續資料的集合 • 透過索引或 key 存取

  4. 數值索引陣列 • $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";

  5. range • Create an array containing a range of elements • array range ( int low, int high [, int step])

  6. <?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; } ?>

  7. 關連式陣列 • $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.

  8. $prices = array("Tires"=>100,"Oil"=>10,"Spark Plugs"=>4); $prices = array("Tires"=>100); $prices["Oil"] = 10; $prices["Spark Plugs"] = 4; 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>"; }

  9. 多維陣列 • $products = array(array("TIR", "Tires", 100),array("OIL", "Oil", 10),array("SPK", "Spark Plugs", 4)); • $product[0][0] 即 "TIR"

  10. 陣列排序 • 數值索引陣列 • sort() 升冪(從小到大)排序 • 關連式陣列 • asort() • Sort an array and maintain index association • ksort() • Sort an array by key • 逆向排序(降冪,從大到小) • rsort()、arsort()、krsort()

  11. $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 = apple b = banana d = lemon a = orange

  12. $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 = orange b = banana c = apple d = lemon

  13. 在多維陣列中排序 • 自行定義物件比較大小的方式,把多維陣列當作物件的一維陣列排序 • 自行定義物件比較大小的函式,傳入參數:兩個物件,傳回值: • =0 兩個物件相等 • >0 第一個物件比較大 • <0 第二個物件比較大 • void usort ( array array, callback cmp_function) • Sort an array by values using a user-defined comparison function • 逆向使用者自訂排序 • kusort()

  14. 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: 6 1: 5 2: 3 3: 2 4: 1

  15. 對陣列重新排序 • shuffle() 亂排 • This function shuffles (randomizes the order of the elements in) an array. • You must use srand() to seed this function.

  16. 相反的順序 • 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);

  17. Array ( [0] => Array ( [0] => green [1] => red ) [1] => 4 [2] => php ) Array ( [2] => Array ( [0] => green [1] => red ) [1] => 4 [0] => php ) 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:

  18. 由檔案載入陣列範例: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.

  19. 由檔案載入陣列範例: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])

  20. 其他陣列操作 • 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

  21. 對陣列中每一個元素逐一進行運算 • array_walk -- Apply a user function to every member of an array • int array_walk ( array array, callback function [, mixed userdata])

  22. <?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'); ?>

  23. The printout of the program above will be: Before ...: d. lemon a. orange b. banana c. apple ... and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple

  24. 計算陣列元素個數 • 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.

  25. 將陣列轉純量變數 • 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:

  26. 將陣列轉純量變數 • 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.

More Related