How to order “zebra” array so each key has an alternate value (either 1, 0)

Same idea to split the input into the 1’s and 0’s, then output a 0 and a 1 as long as there is something left to output. As each time you output a value, the array is reduced, this just continues till both lists are empty so should cope with unbalanced lists…

$temp = [ 0 => [], 1 => []];

foreach($args as $key=>$value){
    $temp[$value['zebra']][] = $key;
}

$output = [];
while ( !empty($temp[0]) || !empty($temp[1]) )   {
    if ( !empty($temp[0]) )   {
        $next = array_shift($temp[0]);
        $output [$next] = $args[$next];
    }
    if ( !empty($temp[1]) )   {
        $next = array_shift($temp[1]);
        $output [$next] = $args[$next];
    }
}

Leave a Comment