|
Posted by Janwillem Borleffs on 05/21/06 02:29
Paul Lautman wrote:
> I understand a bit more about it now, having tried something else,
> but I still can't find a difference between usort and uasort and
> neither can I figure out how to use uksort?
>
What is going wrong in the code from your previous post is that you are
using numeric indexes on associative arrays, contained in $x and $y, which
are using keys instead.
Compare the following implementation with the one from your previous post:
function compare($a, $b) {
list(,$var_a) = array_values($a);
list(,$var_b) = array_values($b);
if ($var_a == $var_b) return 0;
return $var_a < $var_b ? -1 : 1;
}
As you will see, list extracts the value from the second index from the
array returned by array_values when applied to $a and $b.
The difference between usort and uasort, is that the latter preserves the
index association, while the first doesn't. As an example, with usort, the
result will always be:
array( 0 => ..., 1 => ....);
while with uasort, depending on the structure of the original array, the
result can be:
array( 1 => ..., 0 => ....);
The uksort function uses the keys/indexes, while the uasort function uses
the values for sorting. For the array structure you've posted, uksort
appears to be useless.
JW
[Back to original message]
|