php数组的例子

如题所述

php 中的数组类型有非常多的用途,因此这里有一些例子展示数组的完整威力。
<?php// this$a = array( 'color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 );// is completely equivalent with$a['color'] = 'red';$a['taste'] = 'sweet';$a['shape'] = 'round';$a['name'] = 'apple';$a[] = 4; // key will be 0$b[] = 'a';$b[] = 'b';$b[] = 'c';// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),// or simply array('a', 'b', 'c')?>
例子 11-6. 使用 array()
<?php// Array as (property-)map$map = array( 'version' => 4, 'OS' => 'Linux', 'lang' => 'english', 'short_tags' => true );// strictly numerical keys$array = array( 7, 8, 0, 156, -10 );// this is the same as array(0 => 7, 1 => 8, ...)$switching = array( 10, // key = 0 5 => 6, 3 => 7, 'a' => 4, 11, // key = 6 (maximum of integer-indices was 5) '8' => 2, // key = 8 (integer!) '02' => 77, // key = '02' 0 => 12 // the value 10 will be overwritten by 12 );// empty array$empty = array();?>例子 11-7. 集合
<?php$colors = array('red', 'blue', 'green', 'yellow');foreach ($colors as $color) { echo Do you like $color?/n;}?>上例将输出: Do you like red?Do you like blue?Do you like green?Do you like yellow? 直接改变数组的值在 php 5 中可以通过引用传递来做到。之前的版本需要需要采取别的方法:
例子 11-8. 集合
<?php// php 5foreach ($colors as &$color) { $color = strtoupper($color);}unset($color); /* 确保下面对 $color 的覆盖不会影响到前一个数组单元 */// 之前版本的方法foreach ($colors as $key => $color) { $colors[$key] = strtoupper($color);}print_r($colors);?>上例将输出: Array( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW) 本例产生一个基于一的数组。
例子 11-9. 基于一的数组
<?php$firstquarter = array(1 => 'January', 'February', 'March');print_r($firstquarter);?>上例将输出: Array( [1] => 'January' [2] => 'February' [3] => 'March')*/?> 例子 11-10. 填充数组
<?php// fill an array with all items from a directory$handle = opendir('.');while (false !== ($file = readdir($handle))) { $files[] = $file;}closedir($handle);?>数组是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见数组函数。可以用 count() 函数来数出数组中元素的个数。
例子 11-11. 数组排序
<?phpsort($files);print_r($files);?>因为数组中的值可以为任意值,也可是另一个数组。这样可以产生递归或多维数组。
例子 11-12. 递归和多维数组
<?php$fruits = array ( fruits => 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 aboveecho $fruits[holes][5]; // prints secondecho $fruits[fruits][a]; // prints orangeunset($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?>

温馨提示:答案为网友推荐,仅供参考
相似回答