我来自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
)
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/