From PHP 4.1.0, the original position may change when the value of the usort is compared, as in the document:
If Compare as equal, their order in the sorted array is undefined.
That is, if the 2 values of the comparison are the same, their order in the sort results is random. If you need to maintain the original location of the same value, you can refer to the method in this article.
Demo data:
Copy CodeThe code is as follows:
/*
Solve problems in PHP where Usort changes the original position at the same value
Author: artlover http://www.CodeBit.cn
*/
$arr = Array (
Array (' a ' = = 5, ' b ' = + 3),
Array (' a ' = = 5, ' b ' = + 1),
Array (' a ' = = 5, ' b ' = + 4),
Array (' a ' = = 5, ' b ' = + 2),
);
?>
The value of the first element in the array is the same, and the desired result is to keep the existing position unchanged, that is, the order of B is 3,1,4,2
Sort by Usort, when the value of the comparison field is the same, the original order may change
Copy CodeThe code is as follows:
/*
Solve problems in PHP where Usort changes the original position at the same value
Author: artlover http://www.CodeBit.cn
*/
$callback = Create_function (' $a, $b ', ' return ($a ["a"] = = $b ["a"])? 0: (($a ["a"] > $b ["a"])? 1:-1); ');
Usort ($arr, $callback);
?>
Results:
Copy CodeThe code is as follows:
Array
(
[0] = = Array
(
[A] = 5
[B] = 2
)
[1] = = Array
(
[A] = 5
[B] = 4
)
[2] = = Array
(
[A] = 5
[B] = 1
)
[3] = = Array
(
[A] = 5
[B] = 3
)
)
Although the values of the sort fields are the same, usort disrupts the order of the entire array.
If you want to keep the original position at the same time as the value being compared, you can use Array_multisort:
Copy CodeThe code is as follows:
/*
Solve problems in PHP where Usort changes the original position at the same value
Author: artlover http://www.CodeBit.cn
*/
Index counter
$i = 0;
Create 2 empty arrays, the first to save the fields to sort, and the second to save the original index information
$a = $index = Array ();
foreach ($arr as $key = = $data) {
$a [$key] = $data [' a '];
$index [] = $i + +;
}
First array first, followed by the original index row
Array_multisort ($a, SORT_ASC, $index, SORT_ASC, $arr);
?>
Results:
Copy CodeThe code is as follows:
Array
(
[0] = = Array
(
[A] = 5
[B] = 3
)
[1] = = Array
(
[A] = 5
[B] = 1
)
[2] = = Array
(
[A] = 5
[B] = 4
)
[3] = = Array
(
[A] = 5
[B] = 2
)
)
http://www.bkjia.com/PHPjc/324740.html www.bkjia.com true http://www.bkjia.com/PHPjc/324740.html techarticle from PHP 4.1.0, the original position may change when the value of Usort is compared, as in the document: If the members compare as equal, their order in the sorted array is U N . ...