After PHP 4.1.0 and later versions, the original position of usort may change when the compare values are the same. This is what is said in the document:
If two members compare as equal, their order in the sorted array is undefined.
That is to say, if the two values are the same, their order in the sorting result is random. If you need to keep the original position of the same value, refer to the method in this article.
Demo data:
Copy codeThe Code is as follows:
<? Php
/*
Solve the Problem of changing the original position of usort in PHP at the same time.
By 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 values of the first element in the array are the same, and the expected result is to keep the existing position unchanged, that is, the order of B is 3, 1, 4, 2.
Sort by usort. When the values of the Compare fields are the same, the original order may change.
Copy codeThe Code is as follows:
<? Php
/*
Solve the Problem of changing the original position of usort in PHP at the same time.
By 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 );
?>
Result:
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 sorting fields are the same, usort disconnects the entire array order.
If you want to keep the original position while comparing values, you can use array_multisort:
Copy codeThe Code is as follows:
<? Php
/*
Solve the Problem of changing the original position of usort in PHP at the same time.
By Artlover http://www.CodeBit.cn
*/
// Index counter
$ I = 0;
// Create two empty arrays. The first stores the fields to be sorted, and the second stores the original index information.
$ A = $ index = array ();
Foreach ($ arr as $ key => $ data ){
$ A [$ key] = $ data ['a'];
$ Index [] = $ I ++;
}
// The first array is first arranged, followed by the original Index
Array_multisort ($ a, SORT_ASC, $ index, SORT_ASC, $ arr );
?>
Result:
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
)
)