I\'m currently trying to sort a multidimensional array by its subvalues. The structure of the array is:
[0] => Array
(
[id] => 87
[
Try strnatcmp():
usort($output, function($a, $b) {
return strnatcmp($b->days_left, $a->days_left);
});
The PHP doc has a comment that has the solution to this problem. A big thanks to that guy.
Here is a function to sort multidimensional arrays with decimal numbers :
function usortWithFloatVals() {
$arguments = func_get_args();
$array = $arguments[0];
$code = '';
for ($c = 1; $c < count($arguments); $c += 2) {
if (in_array($arguments[$c + 1], array("ASC", "DESC"))) {
$code .= 'if ($a["'.$arguments[$c].'"] != $b["'.$arguments[$c].'"]) {';
if ($arguments[$c + 1] == "ASC") {
$code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? -1 : 1); }';
}
else {
$code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? 1 : -1); }';
}
}
}
$code .= 'return 0;';
$compare = create_function('$a,$b', $code);
usort($array, $compare);
return $array;
}
Use it just like how you use usort()
:
usortWithFloatVals($data, function($a, $b) {
return ($a[$_GET['sortby']] - $b[$_GET['sortby']]) ? 1 : -1;
});
See usort docs. Float result will be converted to integer. For correct work use this code:
usort(
$data,
function($a, $b) {
$result = 0;
if ($a[$_GET['sortby']] > $b[$_GET['sortby']]) {
$result = 1;
} else if ($a[$_GET['sortby']] < $b[$_GET['sortby']]) {
$result = -1;
}
return $result;
}
);