I need to sort an array by values, but if values of elements are equal, I need to compare their keys and sort by them.
uasort($pages_arr, function($a, $b){
if ($a == $b){
return ($key_a < $key_b) ? -1 : 1;
}
return ($a < $b) ? -1 : 1;
});
I dont understand, how can I get $key_a and $key_b values (keys of elements $a and $b). Values can be the same, keys aren't; How to resolve this problem?
Try the following, which uses the uksort
function:
uksort($pages_arr, function($key_a, $key_b) use ($pages_arr) {
$a = $pages_arr[$key_a];
$b = $pages_arr[$key_b];
if ($a == $b) {
return ($key_a < $key_b) ? -1 : 1;
}
return ($a < $b) ? -1 : 1;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With