Nearly two days, in doing a project, encountered a data storage ID do key value or data sorting sort_no do array key problem, considering if you use the data store ID as the key value into the array traversal array will not affect the sorting problem, after query and validation, get the answer: The order of the Foreach Traversal array is traversed in the order in which the values are stored in the array, which is a linear traversal that is not affected by the size order of the array key values .
Here is a simple example to describe the problem:
Database Store User:
Self-Increment ID |
Sort number Sort_no |
Values value |
1 |
3 |
Tom |
2 |
2 |
John doe |
3 |
1 |
Harry |
Through the SQL statement: "Select Id,sort_no,value from the user order by Sort_no ASC" to obtain the result:
Self-Increment ID |
Sort number Sort_no |
Values value |
3 |
1 |
Harry |
2 |
2 |
John doe |
1 |
3 |
Tom |
After getting the data, the data is placed in the order of the query results in the array, at this time with the self-increment ID as the key value of the store, the form is as follows:
$userList = Array (3=> "Harry",2=> "John Doe",1=> "Zhang San");
Or: $userList = Array ("3" = "Harry", "2" = "John Doe", "1" = "Zhang San");
If you use foreach to iterate through the $userlist, is the value traversed in the order in which it was stored in the array or by the sort of key value?
Answer: Theorder of the Foreach Traversal array is traversed in the order in which the values are stored in the array , which is a linear traversal. That
foreach ($userList as $value)
{
echo $value. ",";
}
The operating results are: Harry, John Doe, Zhang San,
If a For loop is used, it is not a linear traversal:
foreach ($i = 0; $i < count ($userList); $i + +)
{
echo $userList [$i]. ",";
}
The operating results are: Zhang San, John Doe, Harry,
Specific principles please check the post: http://www.jb51.net/article/30566.htm
Comparison of the efficiency of the foreach, while, for three loop traversal check the post: http://www.jb51.net/article/61086.htm
The relationship between the foreach traversal order of the array in PHP and the key value