each() 返回4個值, list 賦值哪兩個

來源:互聯網
上載者:User
each list

初學php,請問each() 返回4個值, list 賦值哪兩個
$prices = array('Tires' => 100, 'oil' => 10, 'Spark Plugs' => 4);
$item = each($prices);
print_r($item);
echo "
";
reset($prices);
while(list($a, $b) = each($prices)) {
echo "a:$a,b:$b
";
}
?>
each($prices)的值是4個key value 的數組,
Array ( [1] => 100 [value] => 100 [0] => Tires [key] => Tires )

而list($a, $b) = each($prices)) 為什麼會把$item[key],$item[value]賦值給$a, $b,而不是$item[1],$item[value]。
list不應該是順序賦值麼。
網上找了,官方文檔文檔也找了,都沒有準確答案,各位同學求解額


回複討論(解決方案)

有兩個可能你沒看到
1.
list() only works on numerical arrays and assumes the numerical indices start at 0.
也就是,優先使用的是數字索引的值。
2.
list() assigns the values starting with the right-most parameter.
從參數列表的最右邊開始賦值,所以$b 被賦值 0索引的值,也就是Tires ,然後$a被賦值1索引的值,所以是100

觀察如下事實:

list($a, $b) = array('a', 'b');echo "a:$a b:$b\n"; //輸出 a:a b:blist($a, $b) = array(1 => 'a', 0 => 'b');echo "a:$a b:$b\n"; //輸出 a:b b:alist($a, $b) = array('a'=>'a', 'b'=>'b');echo "a:$a b:$b\n"; //輸出 a: b:錯誤資訊: Undefined offset: 1  Undefined offset: 0 

可知 list 是按參數列表的序號依次從數組中提取相應的下標元素的
即列表中的變數的值就是數組下標的值,而與數組中下標的排列次序無關

那麼特別的指出“從參數列表的最右邊開始賦值”的意義何在呢?
請看這樣的寫法
list($a[$b][$c], $b, $c) = array('a', 'b', 'c');print_r($a);
Array
(
[b] => Array
(
[c] => a
)
)
由於 $c、$b 先於 $a 賦值,所以在向 $a[$b][$c] 賦值的時候不會出錯

感謝上面兩位同學,
主要是這句話確實看掉了,
list() only works on numerical arrays and assumes the numerical indices start at 0.
list() 只工作於 索引從 0 開始的 數值數組

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.