这是来自 php 文档的工作示例代码,用于将 list() 与each() 结合使用
<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
?>
输出为
a => apple
b => banana
c => cranberry
我不明白为什么它会这样工作和输出。因为,
来自 API of each() ,它说each()返回一个带有4键/值对的数组。
所以 each($fruit)
应该是这样的:
Array
(
[1] => yy
[value] => yy
[0] => xx
[key] => xx
)
代码:
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
$key
不应该等于 each($fruit)[1]
,并且 $val
等于 each( $fruit)[值]
?
最佳答案
Note:
list()
only works on numerical arrays and assumes the numerical indices start at 0.
换句话说,list
主动按顺序查找数字键。 list($foo, $bar)
要求分配的数组具有键 0
和 1
并将它们分配给 $foo分别是
和 $bar
。这些键在数组本身中的顺序并不重要。
关于PHP。使用 list() 和 every() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10933901/