for example we want to sort this
$users
array according to
"score"
value
$users = array(
[
'id' => 1,
'name' => 'vighac tipovichi',
'score' => 90
],
[
'id' => 2,
'name' => 'sxva tipson',
'score' => 100
],
);
__________________________________________
1st method is using this custom function:
array_sort($users, 'score', SORT_DESC)
function array_sort($array, $on, $order=SORT_ASC){
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
__________________________________________
2nd method is by using
usort
built-in function which allows us to use "user defined" callback/function to sort array:
1.either by declaring another function dedicated to sort array as you wish
function custom_sort_users($a, $b) {
if ($a['score'] == $b['score']) {
return 0;
}
return ($a['score'] > $b['score']) ? -1 : 1;
}
usort($users, "custom_sort_users");
2.or using callback:
usort($users, function($a, $b){
if ($a['score'] == $b['score']) {
return 0;
}
return ($a['score'] > $b['score']) ? -1 : 1;
});