php - PHP 关联数组是有序的吗?

标签 php arrays dictionary

我来自python背景,类似的python数据类型(字典)是一组无序键值对。

我想知道 PHP 关联数组是否是无序的?它们似乎是有序的。

$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但它并没有对这个问题提供太多的启示。我很欣赏你的回应。类型

最佳答案

PHP 关联数组(以及数字数组)是有序的,PHP 提供了各种函数来处理数组键排序,例如 ksort() , uksort() , 和 krsort()

此外,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
)

From the documentation:

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 - PHP 关联数组是有序的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10914730/

相关文章:

php - DDD、PHP - 在哪里执行验证?

php - 魔术方法 __call() 参数作为 "real"参数

php - 如何停止缓存 jquery php 加载的结果

c - 打印 void 指针的值

c# - 如何初始化 ConcurrentDictionary?错误 : "Cannot access private method ' Add' here"

php - 获取Youtube实时聊天URL,然后重定向到该URL

arrays - 不能在赋值中使用 make([]Entry, 0, 100) (type []Entry) 作为类型 Map

c - 创建并返回数组的函数导致问题

python - 如何获取 Python 函数中命名参数的字典

python-2.7 - 用于实时分析的正确 Python 数据结构?