Home > Backend Development > PHP Tutorial > list()和each()有关问题

list()和each()有关问题

WBOY
Release: 2016-06-13 12:18:13
Original
994 people have browsed it

list()和each()问题

本帖最后由 u014402634 于 2015-04-02 21:06:29 编辑
<br />$fruit = array('a' =>'apple','b'=>'banana','c'=>'cranberry' );<br />reset($fruit);<br />while (list($key,$val)=each($fruit))<br />{<br />	echo "$key=>$val<br>";<br />}<br />//------------------------------------------------------------------------<br /><br /><br />each()不是由4个元素构成么<br />比如第一个是 Array ( [1] => apple [value] => apple [0] => a [key] => a )<br />看手册说list()是从最右边参数开始赋值的  <br />each()4个元素究竟怎么赋值给list两个元素  按理说不是把前两个apple赋值给$key和$val了吗? <br />为啥最后echo能正常输出 对应的 键值对 呢?<br /><br />
Copy after login


------解决思路----------------------
你不看手册的吗?
注: list() 仅能用于数字索引的数组并假定数字索引从 0 开始。

$fruit = array('a' =>'apple');<br />print_r(each($fruit));<br />
Copy after login
Array<br />(<br />    [1] => apple<br />    [value] => apple<br />    [0] => a<br />    [key] => a<br />)<br />
Copy after login
reset($fruit);<br />list($key, $value) = each($fruit);<br />echo "$key => $value";<br />
Copy after login
a => apple
Copy after login
只有数字索引的部分被指派
这样清楚点
$ar = array('a', 'b', 'c' => 'c');<br />list($a, $b, $c) = $ar; //会有 Undefined offset: 2 警告<br />echo "$a $b $c\n";<br />
Copy after login

是按下标递增分配的
$ar = array(1 => 'a', 2 => 'b', 0 => 'c');<br />list($a, $b, $c) = $ar;<br />echo "$a $b $c\n";<br />
Copy after login
c a b
Copy after login
是从右往左分配的
$ar = array('a', 'b', 'c');<br />list($aa[$b][$c], $b, $c) = $ar;<br />print_r($aa);
Copy after login
Array<br />(<br />    [b] => Array<br />        (<br />            [c] => a<br />        )<br /><br />)<br />
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template