Search code examples
phparrayssortingcustom-sort

Sort flat array elements in an alternating fashion so that the last positioned element becomes the new middle element


I've been trying to get my head around this but I can't seem to find a good way to do this, so basically what I'm trying to achieve is sorting array in a way that numbers are sorted for example like this:

Array output (unsorted)
7777777777
7777777777
6666666666
6666666666
2222222222

Array output (sorted)
7777777777
6666666666
2222222222
6666666666
7777777777

I was thinking about making an array NxN and sort it in a way that if there are like 2 array elements of sevens and sixes it will sort them like

7
6
6
7

and all odd numbers like in this exemple 2 it will sort them like

7
6
2
6
7

Solution

  • Count the values in the array.

    $values = array_count_values($array);
    

    (You can asort($values); or arsort($values); after this if you want larger groups of even values to be sorted toward the inside or outside of the symmetrical part of the result array. Or if you don't care, don't.)

    Build arrays of evens and odds based on those counts.

    foreach ($values as $value => $count) {
        if ($count % 2) {
            while ($count--) $odds[] = $value;
        } else {
            $count /= 2;  // half the size, so half can go at the beginning and half at the end
            while ($count--) $evens[] = $value;
        }
    }
    

    Merge the even and odd arrays together to create the result.

    $result = array_merge($evens, $odds, array_reverse($evens));