14. PHP Array数组(2)

来源:互联网 发布:java生成二维码图片 编辑:程序博客网 时间:2024/06/06 01:41

实用函数
有很多操作数组的函数,参见数组函数一节。

Note:

unset() 函数允许删除数组中的某个键。但要注意数组将不会重建索引。如果需要删除后重建索引,可以用 array_values() 函数。

<?php$a = array(1 => 'one', 2 => 'two', 3 => 'three');unset($a[2]);/* will produce an array that would have been defined as   $a = array(1 => 'one', 3 => 'three');   and NOT   $a = array(1 => 'one', 2 =>'three');*/$b = array_values($a);// Now $b is array(0 => 'one', 1 =>'three')?> 

foreach 控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。

数组做什么和不做什么


为什么 $foo[bar] 错了?

应该始终在用字符串表示的数组索引上加上引号。例如用 foo[bar]foo[bar]。但是为什么呢?可能在老的脚本中见过如下语法:

<?php$foo[bar] = 'enemy';echo $foo[bar];// etc?> 

这样是错的,但可以正常运行。那么为什么错了呢?原因是此代码中有一个未定义的常量(bar)而不是字符串(’bar’-注意引号),而 PHP 可能会在以后定义此常量,不幸的是你的代码中有同样的名字。它能运行,是因为 PHP 自动将裸字符串(没有引号的字符串且不对应于任何已知符号)转换成一个其值为该裸字符串的正常字符串。例如,如果没有常量定义为 bar,PHP 将把它替代为 ‘bar’ 并使用之。

Note: **这并不意味着总是给键名加上引号。用不着给键名为常量或变量的加上引号,否则会使 PHP 不能解析它们**。 
Checking 0: Notice: Undefined index:  $i in /path/to/script.html on line 9Bad: Good: 1Notice: Undefined index:  $i in /path/to/script.html on line 11Bad: Good: 1Checking 1: Notice: Undefined index:  $i in /path/to/script.html on line 9Bad: Good: 2Notice: Undefined index:  $i in /path/to/script.html on line 11Bad: Good: 2

演示此行为的更多例子:

<?php// Show all errorserror_reporting(E_ALL);$arr = array('fruit' => 'apple', 'veggie' => 'carrot');// Correctprint $arr['fruit'];  // appleprint $arr['veggie']; // carrot// Incorrect.  This works but also throws a PHP error of level E_NOTICE because// of an undefined constant named fruit// // Notice: Use of undefined constant fruit - assumed 'fruit' in...print $arr[fruit];    // apple// This defines a constant to demonstrate what's going on.  The value 'veggie'// is assigned to a constant named fruit.define('fruit', 'veggie');// Notice the difference nowprint $arr['fruit'];  // appleprint $arr[fruit];    // carrot// The following is okay, as it's inside a string. Constants are not looked for// within strings, so no E_NOTICE occurs hereprint "Hello $arr[fruit]";      // Hello apple// With one exception: braces surrounding arrays within strings allows constants// to be interpretedprint "Hello {$arr[fruit]}";    // Hello carrotprint "Hello {$arr['fruit']}";  // Hello apple// This will not work, and will result in a parse error, such as:// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'// This of course applies to using superglobals in strings as wellprint "Hello $arr['fruit']";print "Hello $_GET['foo']";// Concatenation is another optionprint "Hello " . $arr['fruit']; // Hello apple?> 

当打开 error_reporting 来显示 E_NOTICE 级别的错误(将其设为 E_ALL)时将看到这些错误。默认情况下 error_reporting 被关闭不显示这些。

和在语法一节中规定的一样,在方括号(”[“和”]”)之间必须有一个表达式。这意味着可以这样写:

<?phpecho $arr[somefunc($bar)];?> 

这是一个用函数返回值作为数组索引的例子。PHP 也可以用已知常量,可能之前已经见过:

<?php$error_descriptions[E_ERROR]   = "A fatal error has occured";$error_descriptions[E_WARNING] = "PHP issued a warning";$error_descriptions[E_NOTICE]  = "This is just an informal notice";?> 

?>

注意 E_ERROR 也是个合法的标识符,就和第一个例子中的 bar 一样。但是上一个例子实际上和如下写法是一样的:

<?php$error_descriptions[1] = "A fatal error has occured";$error_descriptions[2] = "PHP issued a warning";$error_descriptions[8] = "This is just an informal notice";?> 

因为 E_ERROR 等于 1,等等。

那么为什么这样做不好?

也许有一天,PHP 开发小组可能会想新增一个常量或者关键字,或者用户可能希望以后在自己的程序中引入新的常量,那就有麻烦了。例如已经不能这样用 empty 和 default 这两个词了,因为他们是保留字。

Note: 重申一次,在双引号字符串中,不给索引加上引号是合法的因此 "$foo[bar]" 是合法的("合法"的原文为 valid。在实际测试中,这么做确实可以访问数组的该元素,但是会报一个常量未定义的 notice。无论如何,强烈建议不要使用 $foo[bar]这样的写法,而要使用 $foo['bar'] 来访问数组中元素。--haohappy 注)。至于为什么参见以上的例子和字符串中的变量解析中的解释。

转换为数组


对于任意 integer,float,string,boolean 和 resource 类型,如果将一个值转换为数组,将得到一个仅有一个元素的数组,其下标为 0,该元素即为此标量的值。换句话说,(array)scalarValuearray(scalarValue) 完全一样。

如果一个 object 类型转换为 array,则结果为一个数组,其单元为该对象的属性。键名将为成员变量名,不过有几点例外:整数属性不可访问;私有变量前会加上类名作前缀;保护变量前会加上一个 ‘*’ 做前缀。这些前缀的前后都各有一个 NULL 字符。这会导致一些不可预知的行为:
对于任意 integer,float,string,boolean 和 resource 类型,如果将一个值转换为数组,将得到一个仅有一个元素的数组,其下标为0,该元素即为此标量的值。换句话说,(array)scalarValuearray(scalarValue) 完全一样。

如果一个 object 类型转换为 array,则结果为一个数组,其单元为该对象的属性。键名将为成员变量名,不过有几点例外:整数属性不可访问;私有变量前会加上类名作前缀;保护变量前会加上一个 ‘*’ 做前缀。这些前缀的前后都各有一个 NULL 字符。这会导致一些不可预知的行为:

<?phpclass A {    private $A; // This will become '\0A\0A'}class B extends A {    private $A; // This will become '\0B\0A'    public $AA; // This will become 'AA'}var_dump((array) new B());?> 

上例会有两个键名为 ‘AA’,不过其中一个实际上是 ‘\0A\0A’。

将 NULL 转换为 array 会得到一个空的数组。

比较

可以用 array_diff() 和数组运算符来比较数组。

示例


PHP 中的数组类型有非常多的用途。以下是一些示例:

<?php// This:$a = array( 'color' => 'red',            'taste' => 'sweet',            'shape' => 'round',            'name'  => 'apple',            4        // key will be 0          );$b = array('a', 'b', 'c');// . . .is completely equivalent with this:$a = array();$a['color'] = 'red';$a['taste'] = 'sweet';$a['shape'] = 'round';$a['name']  = 'apple';$a[]        = 4;        // key will be 0$b = array();$b[] = 'a';$b[] = 'b';$b[] = 'c';// After the above code is executed, $a will be the array// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', // 'name' => 'apple', 0 => 4), and $b will be the array // array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').?> 

Example #8 使用 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();         ?> 

Example #9 集合

<?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 起可以通过引用传递来做到。之前的版本需要需要采取变通的方法:

Example #10 在循环中改变单元

<?php// PHP 5foreach ($colors as &$color) {    $color = strtoupper($color);}unset($color); /* ensure that following writes to$color will not modify the last array element */// Workaround for older versionsforeach ($colors as $key => $color) {    $colors[$key] = strtoupper($color);}print_r($colors);?> 

以上例程会输出:

Array(    [0] => RED    [1] => BLUE    [2] => GREEN    [3] => YELLOW)

本例生成一个下标从 1 开始的数组。

Example #11 下标从 1 开始的数组

<?php$firstquarter  = array(1 => 'January', 'February', 'March');print_r($firstquarter);?> 

以上例程会输出:

Array (    [1] => 'January'    [2] => 'February'    [3] => 'March')

Example #12 填充数组

<?php// fill an array with all items from a directory$handle = opendir('.');while (false !== ($file = readdir($handle))) {    $files[] = $file;}closedir($handle); ?> 

数组是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见数组函数。可以用 count() 函数来数出数组中元素的个数。

Example #13 数组排序

<?phpsort($files);print_r($files);?> 

因为数组中的值可以为任意值,也可是另一个数组。这样可以产生递归或多维数组。

Example #14 递归和多维数组

<?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 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"; ?> 

数组(Array) 的赋值总是会涉及到值的拷贝。使用引用运算符通过引用来拷贝数组。

<?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?> 
0 0
原创粉丝点击