I am trying to sort an array of associative arrays in reverse order by the key of the subarrays.
I solved it with a bubble sort algorithm which worked just fine in my test.
I was wondering if there is a better way, maybe a standard PHP method which I am not aware of.
$list = array(
array(0 => "F"),
array(1 => "E"),
array(60 => "B"),
array(20 => "C"),
array(14 => "D"),
array(100 => "A"),
);
$tmp = [];
for($x = 0; $x < sizeof($list); $x++) {
for($i = 0; $i < sizeof($list); $i++) {
if (!isset($list[$i + 1])) { continue; }
$nextVal = key($list[$i + 1]);
$currentVal = key($list[$i]);
if ($nextVal > $currentVal) {
$tmp = $list[$i];
$list[$i] = $list[$i + 1];
$list[$i + 1] = $tmp;
}
}
}
Output:
AFTER:
array(6) {
[0]=>
array(1) {
[100]=>
string(1) "A"
}
[1]=>
array(1) {
[60]=>
string(1) "B"
}
[2]=>
array(1) {
[20]=>
string(1) "C"
}
[3]=>
array(1) {
[14]=>
string(1) "D"
}
[4]=>
array(1) {
[1]=>
string(1) "E"
}
[5]=>
array(1) {
[0]=>
string(1) "F"
}
}
uksort()
I first hyperlinked refers to the keys of the outer array $list. To sort by the "inner arrays' key" seems to work usingusort($list, fn ($x, $y) => key($x) <=> key($y));
. Disclaimer: I never coded PHP (& don't intend to). \$\endgroup\$<
then it works though. I will add a second answer, thx!! \$\endgroup\$