php是否保留了关联数组中的顺序?

时间:2012-07-14 21:02:26

标签: php arrays associative-array

  

可能重复:
  Are PHP Associative Arrays ordered?

如果我用不同的键将项添加到关联数组中,是否保留了加法顺序?如何访问给定元素的“previous”和“next”元素?

2 个答案:

答案 0 :(得分:14)

是的,php数组有一个隐含的顺序。使用resetnextprevcurrent - 或仅foreach loop - 来检查它。

答案 1 :(得分:11)

是的,它确实保留了订单。您可以将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是最相似的数据结构。