Does php conserve order in associative array? [duplicate]

这一生的挚爱 提交于 2019-12-22 04:00:12

问题


Possible Duplicate:
Are PHP Associative Arrays ordered?

If I add items to associative array with different keys, does order of addition conserved? How can I access "previous" and "next" elements of given element?


回答1:


Yes, php arrays have an implicit order. Use reset, next, prev and current - or just a foreach loop - to inspect it.




回答2:


Yes, it does preserve the order. you can think of php arrays as ordered hash maps.

You can think of the elements as being ordered by "index creation time". For example

$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

To summarize, if you're adding an entry where a key doesnt currently exist in the array, the position of the entry will be the end of the list. If you're updating an entry for an existing key, the position is unchanged.

foreach loops over arrays using the natural order demonstrated above. You can also use next() current() prev() reset() and friends, if you like, although they're rarely used since foreach was introduced into the language.

also, print_r() and var_dump() output their results using the natural array order too.

If you're familiar with java, LinkedHashMap is the most similar data structure.



来源:https://stackoverflow.com/questions/11487374/does-php-conserve-order-in-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!