After 4.1.0 from PHP, the original location may change as the value of the usort is compared, as the document says:
If two members 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 keep the original position of the same value, you can refer to the method in this article.
Demo data:
Copy Code code as follows:
<?php
/*
Solve the problem that usort in PHP 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
Sorted with Usort, the original order may change when comparing the values of the fields
Copy Code code as follows:
<?php
/*
Solve the problem that usort in PHP 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 Code code 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 sorted fields are the same, usort the order of the entire array.
If you want to keep the original position at the same time as the value you are comparing, you can use Array_multisort:
Copy Code code as follows:
<?php
/*
Solve the problem that usort in PHP changes the original position at the same value
Author: artlover http://www.CodeBit.cn
*/
Index counters
$i = 0;
Creates 2 empty arrays, the first saves the fields to sort, and the second saves the original index information
$a = $index = Array ();
foreach ($arr as $key => $data) {
$a [$key] = $data [' a '];
$index [] = $i + +;
}
The first array is sorted first, followed by the original index row
Array_multisort ($a, SORT_ASC, $index, SORT_ASC, $arr);
?>
Results:
Copy Code code 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
)