phparrayssortingnumberscustom-sort

Sort an ascending associative array to alternate lowest values to start or end of the array with the highest value moved to the middle


I have the following type of array :

$foo = [
    "a" => 1,
    "b" => 1,
    "c" => 2,
    "d" => 2,
    "e" => 3,
    "f" => 3,
    "g" => 4,
    "h" => 4,
    "i" => 5,
    "j" => 5,
    "k" => 10,
    "l" => 12,
    "m" => 15,
    "n" => 20
];

I need to sort the array in this way :

$foo = array(1,2,3,4,5,12,20,15,10,5,4,3,2,1);

As you can see, the best value needs to be in the middle of the array. And the min-values in the start/end of array. The key needs to be linked to the original value.


Solution

  • If the input is already sorted, you can use two loops to first push every item with an odd offset in ascending order and then every item with an even offset in descending order into your array:

    $keys = array_keys($foo);
    $n = count($keys);
    $result = array();
    for ($i=0; $i<$n; $i+=2) {
        $result[$keys[$i]] = $foo[$keys[$i]];
    }
    for ($i=$n-$n%2-1; $i>0; $i-=2) {
        $result[$keys[$i]] = $foo[$keys[$i]];
    }