Search code examples
phparrayssortingsequential

Sort a flat array in recurring ascending sequences


I am trying to sort it in a repeating, sequential pattern of numerical order with the largest sets first.

Sample array:

$array = [1,1,1,2,3,2,3,4,5,4,4,4,5,1,2,2,3];

In the above array, I have the highest value of 5 which appears twice so the first two sets would 1,2,3,4,5 then it would revert to the second, highest value set etc.

Desired result:

[1,2,3,4,5,1,2,3,4,5,1,2,3,4,1,2,4]

I am pretty sure I can split the array into chunks of the integer values then cherrypick an item from each subarray sequentially until there are no remaining items, but I just feel that this is going to be poor for performance and I don't want to miss a simple trick that PHP can already handle.


Solution

  • You can use only linear logic to sort using php functions. Here is optimized way to fill data structures. It can be used for streams, generators or anything else you can iterate and compare.

    $array = array(1,1,1,2,3,2,3,4,5,4,4,4,5,1,2,2,3);
    sort($array);
    $chunks = [];
    $index = [];
    foreach($array as $i){
        if(!isset($index[$i])){
            $index[$i]=0;
        }
        if(!isset($chunks[$index[$i]])){
            $chunks[$index[$i]]=[$i];
        } else {
            $chunks[$index[$i]][] = $i;
        }
        $index[$i]++;
    }
    $result = call_user_func_array('array_merge', $chunks);
    print_r($result);