Sort an array by a child array's value in PHP
You can make use of usort function as:
$arr = array(
array("105945","First name",0.080878465391),
array("109145","Second name",0.0504154818384)
);
function cmp($a, $b) {
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] < $b[2]) ? -1 : 1;
}
usort($arr,"cmp");
As of PHP >= 7.0 you can use usort in combination with the spaceship operator
usort($arr, function ($a, $b) {
return $a[2] <=> $b[2];
});
see: http://php.net/manual/de/migration70.new-features.php
For database like patterns use array_multisort as seen in example #3.
For example:
$sort = array();
foreach ($data as $key => $row) {
$sort[$key] = $row['basis'];
}
array_multisort($sort, SORT_ASC, $data);
where $data
is your data array and basis
is the element used for sorting.