PHP 关联数组是有序的吗? [英] Are PHP Associative Arrays ordered?
问题描述
我来自 python 背景,类似的 python 数据类型(字典)是一组无序键值对.
I come from python background and the python datatype which is similar (a dictionary) is an unordered set of key value pairs.
我想知道 PHP 关联数组是否是无序的?它们似乎是有序的.
I am wondering if PHP associative arrays are unordered? They appear to be ordered.
$test = array(
'test' => 'test',
'bar' => 'bar',
);
var_dump($test);
var_dump(array_slice($test, 0, 1));
测试总是在 bar 之前出现,我可以像你看到的那样切分这个数组.那么这是否总是保证跨 php 版本订购?顺序只是我声明数组的顺序吗?所以有些东西在内部指向测试"以将 [0] 放在数组中?我已阅读 http://php.net/manual/en/language.types.array.php 但它并没有过多地说明这个问题.我很欣赏你的回答.类型
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.php but it doesn't shed too much light on this issue. I appreciate your responses. Ty
推荐答案
PHP 关联数组(以及数值数组)是有序的,PHP 提供了各种函数来处理数组键的排序,例如ksort()
, uksort()
和 krsort()
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 允许您使用乱序的数字键声明数组:
Further, PHP allows you to declare arrays with numeric keys out of order:
$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
)
PHP 中的数组实际上是一个有序的映射.映射是一种将值与键相关联的类型.这种类型针对几种不同的用途进行了优化;它可以被视为数组、列表(向量)、哈希表(映射的实现)、字典、集合、堆栈、队列等等.由于数组值可以是其他数组,因此树和多维数组也是可能的.
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 关联数组是有序的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!