For sorting arrays using UDFs, such as uasort (), compare two UDFs:
";if($a==$b) return 0;return ($a>$b) ? 1 : -1;}function b_sort($a, $b){echo $a . '--' . $b . "
";if($a==$b) return 0;return ($a>$b) ? -1 : 1;}$arr = array('a'=>'what', 'b'=>'where', 'c'=>20, 'd'=>'how');uasort($arr, 'a_sort');print_r($arr);echo "
--------------------
";$arr = array('a'=>'what', 'b'=>'where', 'c'=>20, 'd'=>'how');uasort($arr, 'b_sort');print_r($arr);?>
1. how does a UDF work. For example, a_sort: the first time $ a = 'where', $ B = 'whe'; the second time is $ a = where, $ B = 20 ...... why is this?
2. what does return 0, 1,-1 mean? How does it affect sorting?
Reply to discussion (solution)
For the first time, $ a = 'where', $ B = 'whe'; for the second time, $ a = where, $ B = 20 is the function of sorting rules.
($ A> $ B )? 1:-1; indicates the size from small to large ($ a> $ B )? -1: 1; indicates the value ranges from large to small (numbers are larger than letters)
1. how does a UDF work. For example, a_sort: the first time $ a = 'where', $ B = 'whe'; the second time is $ a = where, $ B = 20 ...... why is this?
$ A, $ B is a parameter defined by the_sort and B _sort methods. each time, the elements to be compared in the array are passed to the $ a and $ B parameters for comparison.
Therefore, $ a and $ B are different each time.
The first $ a = 'where', $ B = 'whe'; the second time is $ a = where, $ B = 20.
Because the comparison process is to compare each element in the array with other elements.
Now $ arr = array ('a' => 'whe', 'B' => 'where', 'C' => 20, 'D '=> 'who ');
Therefore
A B
A c
A d
Comparison
Then
B c
B d
Last
C d
Comparison
2. what does return 0, 1,-1 mean? How does one affect sorting?
0 equals
1>
-1 less
Haha, #1 is not said, #2 is based on the general principle
Why?
Where -- what
Where -- 20
How -- where
What -- how
The custom sorting function adopts the bidirectional bubble algorithm and integrates the Insertion sorting algorithm.
The comparison is expanded from the center to the two ends.
2nd the manual has already made it clear:
A comparison function must return an integer less than, equal to, or greater than zero when the first parameter is considered to be less than, equal to, or greater than the second parameter.
Haha, #1 is not said, #2 is based on the general principle
Why?
Where -- what
Where -- 20
How -- where
What -- how
The custom sorting function adopts the bidirectional bubble algorithm and integrates the Insertion sorting algorithm.
The comparison is expanded from the center to the two ends.
2nd the manual has already made it clear:
A comparison function must return an integer less than, equal to, or greater than zero when the first parameter is considered to be less than, equal to, or greater than the second parameter.
Moderator B indeed