Suz*_*ioc 11 php arrays associative-array
可能重复:
PHP关联数组是否已订购?
如果我用不同的键将项添加到关联数组中,是否保留了加法的顺序?如何访问给定元素的"previous"和"next"元素?
goa*_*oat 13
是的,它确实保留了订单.您可以将php数组视为有序哈希映射.
您可以将元素视为按"索引创建时间"排序.例如
$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
Run Code Online (Sandbox Code Playgroud)
总而言之,如果您要添加一个条目,其中某个键当前不存在于数组中,则该条目的位置将是列表的末尾.如果要更新现有密钥的条目,则位置不变.
使用上面演示的自然顺序foreach遍历数组.如果你愿意的话,你也可以使用next()current()prev()reset()和朋友,尽管他们很少使用,因为foreach被引入语言.
另外,print_r()和var_dump()也使用自然数组顺序输出结果.
如果您熟悉java,LinkedHashMap是最相似的数据结构.
| 归档时间: |
|
| 查看次数: |
5249 次 |
| 最近记录: |