PHP 中的数组实际上是一个有序图。图是一种把 values 映射到 keys 的类型。此类型在很多方面做了优化,因此你可以把它当成真正的数组来使用,或列表(矢量),散列表(是图的一种实现),字典,集合,栈,队列以及更多可能 性。因为可以用另一个 PHP 数组作为值,也可以很容易地模拟树。解释这些结构超出了本手册的范围,但对于每种结构你至少会发现一个例子。要得到这些结构的更多信息,我们建议你参考有 关此广阔主题的外部著作。
AD:
例子 11-8. 填充数组
<?php // fill an array with all items from a directory $handle = opendir('.'); while (false !== ($file = readdir($handle))) { $files[] = $file; } closedir($handle); ?>
|
数组是有序的。你也可以使用不同的排序函数来改变顺序。更多信息参见数组函数库。您可以用 count() 函数来数出数组中元素的个数。
例子 11-9. 数组排序
<?php sort($files); print_r($files); ?> |
因为数组中的值可以为任意值,也可是另一个数组。这样你可以产生递归或多维数组。
例子 11-10. 递归和多维数组
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"; ?> |
您需要注意数组的赋值总是会涉及到值的拷贝。您需要在复制数组时用指向符号(&)。
<?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 ?>
站长资讯网