How can i merge arrays like a gearwheel

Posted by JuKe on Stack Overflow See other posts from Stack Overflow or by JuKe
Published on 2013-10-20T15:08:57Z Indexed on 2013/10/20 15:54 UTC
Read the original article Hit count: 143

Filed under:

i have 3 arrays like this

$a = array(
 0 => 'a1',
 1 => 'a2',
 2 => 'a3'
);

$b = array(
 0 => 'b1',
 1 => 'b2',
 2 => 'b3'
);

$c = array(
 0 => 'c1',
 1 => 'c2',
 2 => 'c3'
);

and i like to have somethink like this:

$r = array(
 0 => 'a1',
 1 => 'b1',
 2 => 'c1',
 3 => 'a2',
 4 => 'b2',
 5 => 'c2',
 6 => 'a3',
 ....
 ...
);

how can i do this, with the opinion of more than 3 arrays

EDIT:

i have tried this:

$a = array(
        0 => 'a1',
        1 => 'a2',
        2 => 'a3',
        3 => 'a4'
    );
    $b = array(
        0 => 'b1',
        1 => 'b2',
        2 => 'b3'
    );
    $c = array(
        0 => 'c1',
        1 => 'c2',
        2 => 'c3',
        3 => 'c3',
        4 => 'c3',
        5 => 'c3'

    );

    $l['a'] = count($a);
    $l['b'] = count($b);
    $l['c'] = count($c);

    arsort($l);
    $largest = key($l);
    $result = array();
    foreach ($$largest as $key => $value) {
        $result[] = $a[$key];
        if(array_key_exists($key, $b)) $result[] = $b[$key];
        if(array_key_exists($key, $c)) $result[] = $c[$key];

    }
    print_r($result);

this work.. but the code isn't nice. so anyone has a better solution?

© Stack Overflow or respective owner

Related posts about php