I have an array which is like this:
Array(
[31] => 1
[30] => 2
[29] => 3
[28] => 4
)
I then use ksort($array) which sorts it as 28, 29, 30, and 31 but the problem with this is the numbers 1-4 go with the values so get reversed. I want 28 to become 1, 29 to become 2 etc.
Is there a way without creating a foreach loop and reconstructing a new array to make this switch?
You can flip the array, sort it, and then flip it back:
$array = array(31 =>1, 30 => 2, 29 => 3, 28 => 4);
$result = array_flip($array);
sort($result);
$result = array_flip($result);
This results in an array sorted by keys, and values integers starting from 0:
Array (
[28] => 0
[29] => 1
[30] => 2
[31] => 3
)
If you want to maintain your existing values then use the array_combine function to merge the sorted keys with the old values:
$result = array_flip($array);
sort($result);
$result = array_combine($result, $array);
The resulting array is then:
Array
(
[28] => 1
[29] => 2
[30] => 3
[31] => 4
)
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