php在关联数组中保存顺序吗


Does php conserve order in associative array?

可能重复:
PHP关联数组是否有序?

如果我用不同的键将项添加到关联数组中,添加顺序是否守恒?如何访问给定元素的"上一个"answers"下一个"元素?

是的,php数组有一个隐式顺序。使用resetnextprevcurrent(或仅使用foreach循环)对其进行检查。

是的,它确实保留了顺序。您可以将php数组看作有序的散列映射。

您可以将元素视为按"索引创建时间"排序。例如

$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()和friends,尽管自从foreach被引入该语言以来,它们很少被使用。

此外,printr()和var_dump()也使用自然数组顺序输出结果。

如果您熟悉java,LinkedHashMap是最相似的数据结构。