I've got an array of arrays like this :
Array(
[id1] => Array (
/* details */
[unique] => 3
)
[id2] => Array (
/* details */
[unique] => 5
[id3] => Array (
/* details */
[unique] => 1
)
)
Question : How could I sort it by the unique
field, so that it is converted like the one following?
Array(
[id2] => Array (
/* details */
[unique] => 5
)
[id1] => Array (
/* details */
[unique] => 3
[id3] => Array (
/* details */
[unique] => 1
)
)
Classical task for usort function:
<?php
$data = array(
"id1" => Array (
"unique" => 3
),
"id2" => Array (
"unique" => 5),
"id3" => Array (
"unique" => 1
),
);
function cmp($a, $b)
// {{{
{
if ($a["unique"] == $b["unique"]) {
return 0;
}
return ($a["unique"] < $b["unique"]) ? 1 : -1;
}
// }}}
usort($data, "cmp");
var_dump($data);
Prints:
array(3) {
[0]=>
array(1) {
["unique"]=>
int(5)
}
[1]=>
array(1) {
["unique"]=>
int(3)
}
[2]=>
array(1) {
["unique"]=>
int(1)
}
}