PHP 关联数组是否有序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10914730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are PHP Associative Arrays ordered?
提问by dm03514
I come from python background and the python datatype which is similar (a dictionary) is an unorderedset of key value pairs.
我来自 python 背景,类似的 python 数据类型(字典)是一组无序的键值对。
I am wondering if PHP associative arrays are unordered? They appear to be ordered.
我想知道 PHP 关联数组是否是无序的?他们似乎是有序的。
$test = array(
'test' => 'test',
'bar' => 'bar',
);
var_dump($test);
var_dump(array_slice($test, 0, 1));
Test always comes before bar and I can slice this array as you see. So is this always guaranteed to be ordered across php versions? Is the order just the order that I have declared the array with? So something is internally pointing 'test' to place [0] in the array? I have read http://php.net/manual/en/language.types.array.phpbut it doesn't shed too much light on this issue. I appreciate your responses. Ty
测试总是在 bar 之前出现,我可以像你看到的那样对这个数组进行切片。那么这是否总是保证跨 php 版本订购?顺序只是我声明数组的顺序吗?所以有些东西在内部指向“测试”以将 [0] 放在数组中?我已经阅读了http://php.net/manual/en/language.types.array.php但它并没有对这个问题有太多的了解。我很欣赏你的回答。泰
采纳答案by Michael Berkowski
PHP associative arrays (as well as numeric arrays) are ordered, and PHP supplies various functions to deal with the array key ordering like ksort(), uksort(), and krsort()
PHP关联阵列(以及数字阵列)是有序的,并且PHP提供的各种功能,以解决诸如数组键排序ksort(),uksort()和krsort()
Further, PHP allows you to declare arrays with numeric keys out of order:
此外,PHP 允许您使用乱序的数字键声明数组:
$a = array(3 => 'three', 1 => 'one', 2 => 'two');
print_r($a);
Array
(
[3] => three
[1] => one
[2] => two
)
// Sort into numeric order
ksort($a);
print_r($a);
Array
(
[1] => one
[2] => two
[3] => three
)
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
PHP 中的数组实际上是一个有序映射。映射是一种将值与键相关联的类型。此类型针对多种不同用途进行了优化;它可以被视为数组、列表(向量)、哈希表(映射的实现)、字典、集合、堆栈、队列等等。由于数组值可以是其他数组,树和多维数组也是可能的。
回答by alexn
The documentationstates:
该文件指出:
An array in PHP is actually an ordered map.
So yes, they are always ordered. Arrays are implemented as a hash table.
所以是的,他们总是被订购。数组是作为哈希表实现的。
回答by Mihai Stancu
From the php manual:
从php 手册:
Arraysare ordered. The order can be changed using various sorting functions. See the array functionssection for more information.
I have relied on the fact that they are ordered and it has worked consistently in every project I've had.
我依赖于这样一个事实,即它们是有序的,并且它在我拥有的每个项目中都一直有效。

