简体   繁体   English

在数组上进行迭代时,PHP中的foreach应该遵循的顺序是什么?

[英]What is the order that foreach in PHP should respect when iterating over an array?

I know that PHP array is not an array, it is actually an ordered hashmap, but it still does not make sense to me why if I run this code: 我知道PHP数组不是数组,它实际上是一个有序的哈希表,但是对于我为什么运行此代码仍然没有意义:

<?php

$teste = [];
$teste[2] = 'Test 2';
$teste[1] = 'Test 1';
$teste[3] = 'Test 3';

foreach ($teste as $t) {
    echo $t;
}

It prints the following: 它打印以下内容:

Test 2
Test 1
Test 3

The result does not make sense to me, shouldn't it be ordered like: 结果对我来说没有意义,是否应该像这样订购:

Test 1
Test 2
Test 3

All arrays in PHP are actually ordered maps . PHP中的所有数组实际上都是有序映射 Thus, the order in which key-value pairs are encountered in the map will depend primarily on the order in which they were added to the map. 因此,在映射中遇到键-值对的顺序将主要取决于将键-值对添加到映射中的顺序。 Arrays with a 0..n-1 index sequence in strict increasing order are simply a special case. 索引顺序为0..n-1数组按严格的递增顺序只是一种特殊情况。 You can test this by doing the following: 您可以通过执行以下操作对此进行测试:

$my_arr = array();
$my_arr[3] = 'd';
$my_arr[1] = 'b';
$my_arr[2] = 'c';
$my_arr[0] = 'a';

// #1
echo json_encode($my_arr, JSON_PRETTY_PRINT) . "\n";

// #2
ksort($my_arr);
echo json_encode($my_arr, JSON_PRETTY_PRINT);

Output for #1: #1的输出:

{
    "3": "d",
    "1": "b",
    "2": "c",
    "0": "a"
}

Output for #2: #2的输出:

[
    "a",
    "b",
    "c",
    "d"
]

Note that the only difference between the two versions of $my_arr is the order of the keys. 请注意, $my_arr的两个版本之间的唯一区别是键的顺序。 Out of order, the array is encoded as an object, but in order the array is encoded as a simple array. 乱序将数组编码为对象,但按顺序将数组编码为简单数组。

Please review the linked section of the documentation for more information about PHP's arrays. 请查看文档的链接部分,以获取有关PHP数组的更多信息。 This is already a well-documented feature of the language. 这已经是该语言的有据可查的功能。 If you desire a strict increasing sort order for your keys, use ksort() as shown in the example above. 如果您希望键的排序顺序严格增加,请使用上面示例中所示的ksort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM