PHP 中的數(shù)組實際上是一個有序圖。圖是一種把 values 映射到 keys 的類型。此類型在很多方面做了優(yōu)化,因此你可以把它當(dāng)成真正的數(shù)組來使用,或列表(矢量),散列表(是圖的一種實現(xiàn)),字典,集合,棧,隊列以及更多可能 性。因為可以用另一個 PHP 數(shù)組作為值,也可以很容易地模擬樹。解釋這些結(jié)構(gòu)超出了本手冊的范圍,但對于每種結(jié)構(gòu)你至少會發(fā)現(xiàn)一個例子。要得到這些結(jié)構(gòu)的更多信息,我們建議你參考有 關(guān)此廣闊主題的外部著作。
AD:
例子 11-8. 填充數(shù)組
<?php // fill an array with all items from a directory $handle = opendir('.'); while (false !== ($file = readdir($handle))) { $files[] = $file; } closedir($handle); ?> |
數(shù)組是有序的。你也可以使用不同的排序函數(shù)來改變順序。更多信息參見數(shù)組函數(shù)庫。您可以用 count() 函數(shù)來數(shù)出數(shù)組中元素的個數(shù)。
例子 11-9. 數(shù)組排序
<?php sort($files); print_r($files); ?> |
因為數(shù)組中的值可以為任意值,也可是另一個數(shù)組。這樣你可以產(chǎn)生遞歸或多維數(shù)組。
例子 11-10. 遞歸和多維數(shù)組
array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3, 4, 5, 6 ), "holes" => array ( "first", 5 => "second", "third" ) ); // Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]); // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good"; ?> |
您需要注意數(shù)組的賦值總是會涉及到值的拷貝。您需要在復(fù)制數(shù)組時用指向符號(&)。
<?php $arr1 = array(2, 3); $arr2 = $arr1; $arr2[] = 4; // $arr2 is changed, // $arr1 is still array(2,3) $arr3 = &$arr1; $arr3[] = 4; // now $arr1 and $arr3 are the same ?>