1.each的用法
先看API
array each ( array &$array )
api裡是這麼描述的:each — 返回數組中當前的鍵/值對並將數組指針向前移動一步
我們先來看看傳回的陣列是怎麼樣的?
<code><span><?php</span><span>$arr</span> = <span>array</span>(<span>'你'</span>,<span>'若'</span>,<span>'安'</span>,<span>'好'</span>,<span>'便'</span>,<span>'是'</span>,<span>'晴'</span>,<span>'天'</span>); print_r(each(<span>$arr</span>)); print_r(each(<span>$arr</span>)); <span>echo</span><span>'<hr />'</span>; <span>/* 返回 Array ( [1] => 你 [value] => 你 [0] => 0 [key] => 0 ) Array ( [1] => 若 [value] => 若 [0] => 1 [key] => 1 ) */</span><span>//执行相同的一段代码,从‘你’到‘若’,说明each是会每执行一次,游标向数组尾部移动一步</span><span>//0和Key存放的是键</span><span>//1和value存放的是值</span><span>//因此each满足遍历数组的,得到当前的键和值,以及每执行一次,向尾部移动一步游标</span><span>//因此循环数组也可以用each这么写</span> reset(<span>$arr</span>); <span>for</span>(;<span>$tmp</span>=each(<span>$arr</span>);){ <span>echo</span><span>$tmp</span>[<span>0</span>],<span>'~'</span>,<span>$tmp</span>[<span>1</span>],<span>'<br />'</span>; } <span>/* 返回 0~你 1~若 2~安 3~好 4~便 5~是 6~晴 7~天 */</span><span>?></span></code>
2.list的用法
先看api是怎麼說的
像 array() 一樣,這不是真正的函數,而是語言結構。 list()用一步操作給一組變數賦值。
來看一個例子:
<code><span><?php</span><span>list</span>(<span>$a</span>,<span>$b</span>)=<span>array</span>(<span>10</span>,<span>20</span>); <span>echo</span><span>$a</span>,<span>'~'</span>,<span>$b</span>,<span>'<br />'</span>; <span>//返回10~20</span><span>?></span></code>
沒錯可以給一組變數賦值
再來看另外一個例子:
<code><span><?php</span><span>list</span>(<span>$a</span>,<span>$b</span>,,<span>$c</span>)=<span>array</span>(<span>2</span>=><span>10</span>,<span>3</span>=><span>20</span>,<span>4</span>=><span>30</span>,<span>1</span>=><span>40</span>); <span>echo</span><span>$a</span>,<span>'~'</span>,<span>$b</span>,<span>'~'</span>,<span>$c</span>,<span>'<br />'</span>; <span>//返回notice~40~20</span><span>//执行到$a的时候返回给我一个notice:说数组没有0键</span><span>?></span></span></code>
按照一般的想法應該會回傳:10~20~40
為什麼會回這個notice~40~20呢?
答: 這牽涉到list的運作機制,list是這麼賦值的
首先:不要管右邊的數組,看List裡面的變量,由左到右應該是<code><span><?php</span><span>$arr</span> = <span>array</span>(<span>'你'</span>,<span>'若'</span>,<span>'安'</span>,<span>'好'</span>,<span>'便'</span>,<span>'是'</span>,<span>'晴'</span>,<span>'天'</span>);
<span>for</span>(;<span>list</span>(<span>$k</span>,<span>$v</span>)=each(<span>$arr</span>);){
<span>echo</span><span>$k</span>,<span>'~'</span>,<span>$v</span>,<span>'<br />'</span>;
}
<span>/*
return:
0~你
1~若
2~安
3~好
4~便
5~是
6~晴
7~天
*/</span><span>?></span></code>