cvs: phpdoc-zh /language/types array.xml

From: Date: Thu, 25 Dec 2008 01:21:43 +0000
Subject: cvs: phpdoc-zh /language/types array.xml
Groups: php.doc.zh 
Request: Send a blank email to doc-zh+get-3136@lists.php.net to get a copy of this message
eniac2008 Thu Dec 25 01:21:43 2008 UTC Added files: /phpdoc-zh/language/types array.xml Log: Sync with EN-Revision 1.7

http://cvs.php.net/viewvc.cgi/phpdoc-zh/language/types/array.xml?view=markup&rev=1.1 Index: phpdoc-zh/language/types/array.xml +++ phpdoc-zh/language/types/array.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <!-- $Author: eniac2008 --> <!-- EN-Revision: 1.7 Maintainer: Altair Status: ready --> <!-- CREDITS: Geogory dallas --> <sect1 xml:id="language.types.array"> <title>数组</title> <para> PHP 中的 <type>数组</type> 实际上是一个有序映射。映射是一种把 <emphasis>values</emphasis> 关联到 <emphasis>keys</emphasis> 的类型。此类型在很多方面做了优化,因此可以把它当成真正的数组,或列表(向量),散列表(是映射的一种实现),字典,集合,栈,队列以及更多可能性。数组元素的值也可以是另一个数组。树形结构和多维数组也是允许的。 </para> <para> 解释这些结构超出了本手册的范围,但对于每种结构至少会提供一个例子。要得到这些结构的更多信息,建议参考有关此广阔主题的其它著作。 </para> <sect2 xml:id="language.types.array.syntax"> <title>语法</title> <sect3 xml:id="language.types.array.syntax.array-func"> <title>定义数组 <function>array</function></title> <para> 可以用 <function>array</function> 语言结构来新建一个 <type>array</type>。它接受任意数量用逗号分隔的 <literal><replaceable>键(key)</replaceable> =&gt; <replaceable>值(value)</replaceable></literal> 对。 </para> <synopsis> array( <optional> <replaceable>key</replaceable> =&gt; </optional> <replaceable>value</replaceable> , ... ) // <replaceable>键(key)</replaceable> 可是是一个 <type>整数(integer)</type> 或 <type>字符串(string)</type> // <replaceable>值(value)</replaceable> 可以是任意类型的值</synopsis> <!-- Do not fix the whitespace for the synopsis end element. A limitation of PhD prevents proper trimming --> <informalexample> <programlisting role="php"> <![CDATA[ <?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?> ]]> </programlisting> </informalexample> <para> <varname>key</varname> 可以是 <type>integer</type> 或者 <type>string</type>。如果key是一个 <type>integer</type> 的标准表示,则被解释为整数(例如 <literal>"8"</literal> 将被解释为 <literal>8</literal>,而 <literal>"08"</literal> 将被解释为 <literal>"08"</literal>)。<varname>key</varname> 中的浮点数被取整为 <type>integer</type>。在 PHP 中索引数组与关联 <type>数组</type> 是相同的,它们都可以同时包含 <type>整型</type> 和 <type>字符串</type> 的下标。 </para> <para> 值可以是任意的 PHP 类型。 </para> <informalexample> <programlisting role="php"> <![CDATA[ <?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42 ?> ]]> </programlisting> </informalexample> <para> 如果对给出的值没有指定键名,则取当前最大的整数索引值,而新的键名将是该值加一。如果指定的键名已经有了值,则该值会被覆盖。 </para> <informalexample> <programlisting role="php"> <![CDATA[ <?php // 这个数组与下面的数组相同 ... array(5 => 43, 32, 56, "b" => 12); // ... array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> ]]> </programlisting> </informalexample> <warning> <simpara> 自 PHP 4.3.0 起,上述的索引生成方法改变了。如今如果给一个当前最大键名是负值的数组添加一个新值,则新生成的的索引将为零(<literal>0</literal>)。以前新生成的索引为当前最大索引加一,和正值的索引相同。 </simpara> </warning> <para> 使用 &true; 作为键名将使 <type>integer</type> <literal>1</literal> 成为键名。使用 &false; 作为键名将使 <type>integer</type> <literal>0</literal> 成为键名。使用 <literal>NULL</literal> 作为键名将等同于使用空字符串。使用空字符串作为键名将新建(或覆盖)一个用空字符串作为键名的值,这和用空的方括号不一样。 </para> <para> 不能用数组和对象作为键(key)。这样做会导致一个警告:<literal>Illegal offset type</literal>。 </para> </sect3> <sect3 xml:id="language.types.array.syntax.modifying"> <title>用方括号的语法新建/修改</title> <para> 可以通过明示地设定值来改变一个现有的数组。 </para> <para> 这是通过在方括号内指定键名来给数组赋值实现的。也可以省略键名,在这种情况下给变量名加上一对空的方括号(“<literal>[]</literal>”)。 </para> <synopsis> $arr[<replaceable>key</replaceable>] = <replaceable>value</replaceable>; $arr[] = <replaceable>value</replaceable>; // <replaceable>key</replaceable> 可以是 <type>integer</type> 或 <type>string</type> // <replaceable>value</replaceable> 可以是任意类型的值</synopsis> <para> 如果 <varname>$arr</varname> 还不存在,将会新建一个。这也是一种定义数组的替换方法。要改变一个值,只要给它赋一个新值。如果要删除一个键名/值对,要对它用 <function>unset</function>。 </para> <informalexample> <programlisting role="php"> <![CDATA[ <?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> ]]> </programlisting> </informalexample> <note> <para> 如上所述,如果给出方括号但没有指定键名,则取当前最大整数索引值,新的键名将是该值 + 1。如果当前还没有整数索引,则键名将为 <literal>0</literal>。如果指定的键名已经有值了,该值将被覆盖。 </para> <para> 注意这里所使用的最大整数键名<emphasis>不一定</emphasis>当前就在数组中。它只要在上次数组重新生成索引后曾经存在过就行了。以下面的例子来说明: </para> <informalexample> <programlisting role="php"> <![CDATA[ <?php // 创建一个简单的数组 $array = array(1, 2, 3, 4, 5); print_r($array); // 现在删除其中的所有元素,但保持数组本身不变: foreach ($array as $i => $value) { unset($array[$i]); } print_r($array); // 添加一个单元(注意新的键名是 5,而不是你可能以为的 0) $array[] = 6; print_r($array); // 重新索引: $array = array_values($array); $array[] = 7; print_r($array); ?> ]]> </programlisting> &example.outputs; <screen> <![CDATA[ Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 ) ]]> </screen> </informalexample> </note> </sect3> </sect2><!-- end syntax --> <sect2 xml:id="language.types.array.useful-funcs"> <title>实用函数</title> <para> 有很多操作数组的函数,参见<link linkend="ref.array">数组函数</link>一节。 </para> <note> <para> <function>unset</function> 函数允许删除数组中的某个键。但要注意数组将不会重建索引。 If a true "remove and shift" behavior is desired, the <type>array</type> can be reindexed using the <function>array_values</function> function. </para> <informalexample> <programlisting role="php"> <![CDATA[ <?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') ?> ]]> </programlisting> </informalexample> </note> <para> <link linkend="control-structures.foreach">foreach</link> 控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。 </para> </sect2> <sect2 xml:id="language.types.array.donts"> <title>数组做什么和不做什么</title> <sect3 xml:id="language.types.array.foo-bar"> <title>为什么 <literal>$foo[bar]</literal> 错了?</title> <para> 应该始终在用字符串表示的数组索引上加上引号。例如用 $foo['bar'] 而不是 $foo[bar]。但是为什么 $foo[bar] 错了呢?可能在老的脚本中见过如下语法: </para> <informalexample> <programlisting role="php"> <![CDATA[ <?php $foo[bar] = 'enemy'; echo $foo[bar]; // etc ?> ]]> </programlisting> </informalexample> <para> 这样是错的,但可以正常运行。那么为什么错了呢?原因是此代码中有一个未定义的常量(bar)而不是字符串('bar'-注意引号),而 PHP 可能会在以后定义此常量,不幸的是你的代码中有同样的名字。它能运行,是因为 PHP 自动将<emphasis>裸字符串</emphasis>(没有引号的字符串且不对应于任何已知符号)转换成一个其值为该裸字符串的正常字符串。例如,如果没有常量定义为 <constant>bar</constant>,PHP 将把它替代为 <literal>'bar'</literal> 并使用之。 </para> <note> <simpara> 这并不意味着<emphasis>总是</emphasis>给键名加上引号。用不着给键名为<link linkend="language.constants">常量</link>或<link linkend="language.variables">变量</link>的加上引号,否则会使 PHP 不能解析它们。 </simpara> <informalexample> <programlisting role="php"> <![CDATA[ <?php error_reporting(E_ALL); ini_set('display_errors', true); ini_set('html_errors', false); // Simple array: $array = array(1, 2); $count = count($array); for ($i = 0; $i < $count; $i++) { echo "\nChecking $i: \n"; echo "Bad: " . $array['$i'] . "\n"; echo "Good: " . $array[$i] . "\n"; echo "Bad: {$array['$i']}\n"; echo "Good: {$array[$i]}\n"; } ?> ]]> </programlisting> </informalexample> &example.outputs; <screen> <![CDATA[ Checking 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 1 Checking 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 2 ]]> </screen> </note> <para> 演示此行为的更多例子: </para> <informalexample> <programlisting role="php"> <![CDATA[ <?php // Show all errors error_reporting(E_ALL); $arr = array('fruit' => 'apple', 'veggie' => 'carrot'); // Correct print $arr['fruit']; // apple print $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 now print $arr['fruit']; // apple print $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 here print "Hello $arr[fruit]"; // Hello apple // With one exception: braces surrounding arrays within strings allows constants // to be interpreted print "Hello {$arr[fruit]}"; // Hello carrot print "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 well print "Hello $arr['fruit']"; print "Hello $_GET['foo']"; // Concatenation is another option print "Hello " . $arr['fruit']; // Hello apple ?> ]]> </programlisting> </informalexample> <para> 当打开 <link linkend="ini.error-reporting">error_reporting</link> 来显示 <constant>E_NOTICE</constant> 级别的错误(例如将其设为 <constant>E_ALL</constant>)时将看到这些错误。默认情况下 <link linkend="ini.error-reporting">error_reporting</link> 被关闭不显示这些。 </para> <para> 和在<link linkend="language.types.array.syntax">语法</link>一节中规定的一样,在方括号(“<literal>[</literal>”和“<literal>]</literal>”)之间必须有一个表达式。这意味着可以这样写: </para> <informalexample> <programlisting role="php"> <![CDATA[ <?php echo $arr[somefunc($bar)]; ?> ]]> </programlisting> </informalexample> <para> 这是一个用函数返回值作为数组索引的例子。PHP 也可以用已知常量,可能之前已经见过 </para> <informalexample> <programlisting role="php"> <![CDATA[ <?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"; ?> ]]> </programlisting> </informalexample> <para> 注意 <literal>E_ERROR</literal> 也是个合法的标识符,就和第一个例子中的 <literal>bar</literal> 一样。但是上一个例子实际上和如下写法是一样的: </para> <informalexample> <programlisting role="php"> <![CDATA[ <?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"; ?> ]]> </programlisting> </informalexample> <para> 因为 <literal>E_ERROR</literal> 等于 <literal>1</literal>, 等等. </para> <sect4 xml:id="language.types.array.foo-bar.why"> <title>那么为什么这样做不好?</title> <para> 也许有一天,PHP 开发小组可能会想新增一个常量或者关键字,或者用户可能希望以后在自己的程序中引入新的常量,那就有麻烦了。例如已经不能这样用 <literal>empty</literal> 和 <literal>default</literal> 这两个词了,因为他们是<link linkend="reserved">保留字</link>。 </para> <note> <simpara> 重申一次,在双引号字符串中,不给索引加上引号是合法的因此 <literal>"$foo[bar]"</literal>是合法的。至于为什么参见以上的例子和<link linkend="language.types.string.parsing">字符串中的变量解析</link>中的解释。 </simpara> </note> </sect4> </sect3> </sect2> <sect2 xml:id="language.types.array.casting"> <title>转换为数组</title> <para> 对于任意类型: <type>integer</type>, <type>float</type>, <type>string</type>, <type>boolean</type> and <type>resource</type>,如果将一个值转换为数组,将得到一个仅有一个元素的数组(其下标为 0),该元素即为此标量的值。换句话说, <literal>(array)$scalarValue</literal> 与 <literal>array($scalarValue)</literal> 完全一样。 </para> <para> If an <type>object</type> is converted to an <type>array</type>, the result is an <type>array</type> whose elements are the <type>object</type>'s properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour: </para> <informalexample> <programlisting role="php"> <![CDATA[ <?php class 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()); ?> ]]> </programlisting> </informalexample> <para> The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'. </para> <para> 将 &null; 转换到 <type>数组(array)</type> 会得到一个空的数组。 </para> </sect2> <sect2 xml:id="language.types.array.comparing"> <title>比较</title> <para> 可能使用 <function>array_diff</function> 和<link linkend="language.operators.array">数组运算符</link>来比较数组。 </para> </sect2> <sect2 xml:id="language.types.array.examples"> <title>Examples</title> <para> PHP 中的数组类型有非常多的用途,因此这里有一些例子展示数组的完整威力。 </para> <informalexample> <programlisting role="php"> <![CDATA[ <?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'). ?> ]]> </programlisting> </informalexample> <example> <title>Using array()</title> <programlisting role="php"> <![CDATA[ <?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(); ?> ]]> <!-- TODO example of - overwriting keys - using vars/functions as key/values - warning about references --> </programlisting> </example> <example xml:id="language.types.array.examples.loop"> <title>集合</title> <programlisting role="php"> <![CDATA[ <?php $colors = array('red', 'blue', 'green', 'yellow'); foreach ($colors as $color) { echo "Do you like $color?\n"; } ?> ]]> </programlisting> &example.outputs; <screen> <![CDATA[ Do you like red? Do you like blue? Do you like green? Do you like yellow? ]]> </screen> </example> <para> 直接改变数组的值在 PHP 5 中可以通过引用传递来做到。之前的版本需要需要采取变通的方法: </para> <example xml:id="language.types.array.examples.changeloop"> <title>集合</title> <programlisting role="php"> <![CDATA[ <?php // PHP 5 foreach ($colors as &$color) { $color = strtoupper($color); } unset($color); /* ensure that following writes to $color will not modify the last array element */ // Workaround for older versions foreach ($colors as $key => $color) { $colors[$key] = strtoupper($color); } print_r($colors); ?> ]]> </programlisting> &example.outputs; <screen> <![CDATA[ Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW ) ]]> </screen> </example> <para> 本例生成一个下标从1开始的数组。This example creates a one-based array. </para> <example> <title>下标从1开始的数组</title> <programlisting role="php"> <![CDATA[ <?php $firstquarter = array(1 => 'January', 'February', 'March'); print_r($firstquarter); ?> ]]> </programlisting> &example.outputs; <screen> <![CDATA[ Array ( [1] => 'January' [2] => 'February' [3] => 'March' ) ]]> </screen> </example> <example> <title>填充数组</title> <programlisting role="php"> <![CDATA[ <?php // fill an array with all items from a directory $handle = opendir('.'); while (false !== ($file = readdir($handle))) { $files[] = $file; } closedir($handle); ?> ]]> </programlisting> </example> <para> 数组是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见<link linkend="ref.array">数组函数</link>。可以用 <function>count</function> 函数来数出数组中元素的个数。 </para> <example> <title>数组排序</title> <programlisting role="php"> <![CDATA[ <?php sort($files); print_r($files); ?> ]]> </programlisting> </example> <para> 因为数组中的值可以为任意值,也可是另一个数组。这样可以产生递归或多维数组。 </para> <example> <title>递归和多维数组</title> <programlisting role="php"> <![CDATA[ <?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"; ?> ]]> </programlisting> </example> <para> <type>数组(Array)</type> 的赋值总是会涉及到值的拷贝。使用 <link linkend="language.operators">引用操作符</link> 通过引用来拷贝数组。 </para> <informalexample> <programlisting role="php"> <![CDATA[ <?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 ?> ]]> </programlisting> </informalexample> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 -->
« previous php.doc.zh (#3136) next »