Forum und email

陣列

PHP 的陣列同時擁有拼雜表 HASH TABLE 和 索引表 INDEX TABLE 的特性。(關聯字索引式陣列 ASSOCIATIVE ARRAY 和 矢量 VECTOR 就是兩個例子)

單維陣列

在 PHP 中 數值索引式和關聯字索引式這兩類陣列其實上是一樣的。 你可用 list()array() 函數來建立陣列, 也可以直接指定陣列中元素的值。

$a[0] = "abc"; 
$a[1] = "def"; 
$b["foo"] = 13;

假如沒有給出陣列元素的參照標號, PHP 會在陣列最未端加入一個元素, 並把數值存到該元素中去。 用這個特點你可以很簡單地建立一個陣列。

$a[] = "hello"; // $a[2] == "hello"
$a[] = "world"; // $a[3] == "world"

要把陣列中的元素排序, 可按陣列的形態調用 asort(), arsort(), ksort(), rsort(), sort(), uasort(), usort(), uksort() 等函數。

count() 函數會給出陣列中有多少個元素。

你可以用 next()prev()函數來指向陣列中的不同元素, 另一個常用的同類函數是 each().

高維陣列

高維陣列(多維陣列) 的使用其實是很簡單的。 你只要在陣列後面加多一個引數 "[ ]", 陣列便多了一個維數:

$a[1]      = $f;               # one dimensional examples
$a["foo"]  = $f;   

$a[1][0]     = $f;             # two dimensional
$a["foo"][2] = $f;             # (you can mix numeric and associative indices)
$a[3]["bar"] = $f;             # (you can mix numeric and associative indices)

$a["foo"][4]["bar"][0] = $f;   # four dimensional!

PHP3 並不允許直接在文句之中參照多維陣列中的元素。 如下例的程式將產生錯誤的結果。

$a[3]['bar'] = 'Bob';
echo "This won't work: $a[3][bar]";
用 PHP3, 以上運算的結果將是 This won't work: Array[bar]! 對付這個問題要用到 "." 文句拼合運算符才行:
$a[3]['bar'] = 'Bob';
echo "This will work: " . $a[3][bar];

在 PHP4 版本中, 用花括號在文句中把陣列參照包起來就解決了以上的古怪問題 :

$a[3]['bar'] = 'Bob';
echo "This will work: {$a[3][bar]}";

要填滿一個多維的陣列有很多辦法。 但比較難弄懂的是用 array() 函數來指定關聯字索引式陣列 ASSOCIATIVE ARRAY 中的值。 以下兩段程式碼的功能是完全一樣的 :

# Example 1:

$a["color"]    = "red";
$a["taste"]    = "sweet";
$a["shape"]    = "round";
$a["name"]    = "apple";
$a[3]        = 4;

# Example 2:
$a = array(
     "color" => "red",
     "taste" => "sweet",
     "shape" => "round",
     "name"  => "apple",
     3       => 4
);

用巢狀的 array() 函數可以建立出多維的陣列 :

<?php
$a 
= array(
     
"apple"  => array(
          
"color"  => "red",
          
"taste"  => "sweet",
          
"shape"  => "round"
     
),
     
"orange"  => array(
          
"color"  => "orange",
          
"taste"  => "tart",
          
"shape"  => "round"
     
),
     
"banana"  => array(
          
"color"  => "yellow",
          
"taste"  => "paste-y",
          
"shape"  => "banana-shaped"
     
)
);

echo 
$a["apple"]["taste"];    # will output "sweet"
?>