I'm trying to understand how php function usort works. I have such code:
<?php
$users[] = array('login' => 'moon', 'name' => 'Chris');
$users[] = array('login' => 'star', 'name' => 'Piter');
$users[] = array('login' => 'mars', 'name' => 'Tim');
$users[] = array('login' => 'earth', 'name' => 'Garry');
function compare($a, $b) {
echo $a['login'] . '--' . $b['login'] . '<br />';
echo strcmp($a['login'], $b['login']) . '<br />';
return strcmp($a['login'], $b['login']);
}
usort($users, "compare");
echo '<pre>'; print_r($users); echo '</pre>';
?>
It will output such result:
star--moon
1
star--mars
1
earth--star
-1
moon--earth
1
mars--moon
-1
earth--mars
-1
Array
(
[0] => Array
(
[login] => earth
[name] => Garry
)
[1] => Array
(
[login] => mars
[name] => Tim
)
[2] => Array
(
[login] => moon
[name] => Chris
)
[3] => Array
(
[login] => star
[name] => Piter
)
)
As far as I understand second param should be comparison function and it can only return 3 values (-1,0,1) and usort
use this results to sort array? Also I read, usort
use Quicksort implementation to sort array. That is why star is first and moon - second? Quicksort divide array into two parts and then sort it? And can I implement this function for 2,3 dimensions array?