【发布时间】:2012-07-14 07:13:35
【问题描述】:
【问题讨论】:
标签: php arrays associative-array
【问题讨论】:
标签: php arrays associative-array
是的,php 数组有一个隐含的顺序。使用 reset、next、prev 和 current - 或仅使用 foreach loop - 来检查它。
【讨论】:
是的,它确实保留了顺序。您可以将 php 数组视为ordered hash maps。
您可以将元素视为按“索引创建时间”排序。例如
$a = array();
$a['x'] = 1;
$a['y'] = 1;
var_dump($a); // x, y
$a = array();
$a['x'] = 1;
$a['y'] = 1;
$a['x'] = 2;
var_dump($a); // still x, y even though we changed the value associated with the x index.
$a = array();
$a['x'] = 1;
$a['y'] = 1;
unset($a['x']);
$a['x'] = 1;
var_dump($a); // y, x now! we deleted the 'x' index, so its position was discarded, and then recreated
总而言之,如果您要添加一个条目,其中一个键当前不存在于数组中,则该条目的位置将是列表的末尾。如果您要更新现有键的条目,则位置不会改变。
foreach 使用上面演示的自然顺序循环数组。如果你愿意,你也可以使用next() current() prev() reset() 和朋友,尽管自从 foreach 被引入语言以来,它们很少使用。
另外,print_r() 和 var_dump() 也使用自然数组顺序输出它们的结果。
如果你熟悉java,LinkedHashMap是最相似的数据结构。
【讨论】: