Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can i merge arrays like a gearwheel
    text
    copied!<p>i have 3 arrays like this</p> <pre><code>$a = array( 0 =&gt; 'a1', 1 =&gt; 'a2', 2 =&gt; 'a3' ); $b = array( 0 =&gt; 'b1', 1 =&gt; 'b2', 2 =&gt; 'b3' ); $c = array( 0 =&gt; 'c1', 1 =&gt; 'c2', 2 =&gt; 'c3' ); </code></pre> <p>and i like to have somethink like this:</p> <pre><code>$r = array( 0 =&gt; 'a1', 1 =&gt; 'b1', 2 =&gt; 'c1', 3 =&gt; 'a2', 4 =&gt; 'b2', 5 =&gt; 'c2', 6 =&gt; 'a3', .... ... ); </code></pre> <p>how can i do this? and the option to use more then 3 arrays</p> <p><strong>EDIT:</strong></p> <p>i have tried this:</p> <pre><code>$a = array( 0 =&gt; 'a1', 1 =&gt; 'a2', 2 =&gt; 'a3', 3 =&gt; 'a4' ); $b = array( 0 =&gt; 'b1', 1 =&gt; 'b2', 2 =&gt; 'b3' ); $c = array( 0 =&gt; 'c1', 1 =&gt; 'c2', 2 =&gt; 'c3', 3 =&gt; 'c4', 4 =&gt; 'c5', 5 =&gt; 'c6' ); $l['a'] = count($a); $l['b'] = count($b); $l['c'] = count($c); arsort($l); $largest = key($l); $result = array(); foreach ($$largest as $key =&gt; $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); </code></pre> <p>Output: <code>Array ( [0] =&gt; a1 [1] =&gt; b1 [2] =&gt; c1 [3] =&gt; a2 [4] =&gt; b2 [5] =&gt; c2 [6] =&gt; a3 [7] =&gt; b3 [8] =&gt; c3 [9] =&gt; a4 [10] =&gt; c4 [11] =&gt; [12] =&gt; c5 [13] =&gt; [14] =&gt; c6 )</code></p> <p>this work.. but the code isn't nice. so anyone has a better solution?</p> <p><strong>Solution:</strong> i updated the post from @salathe with some dynamic feature</p> <pre><code>function comb(){ $arrays = func_get_args(); $result = array(); foreach (call_user_func_array(array_map, $arrays) as $column) { $values = array_filter($column, function ($a) { return $a !== null; }); $result = array_merge($result, $values); } return $result; } print_r(comb(null,$a,$b,$c,$d,....)); </code></pre> <p>Thanks to all!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload