Is there a native PHP function to zip merge two arrays?
Look at the following example:
$a = array("a","b","c");
$b = array("d","e","f");
$c = array("g","h","i");
var_dump(array_merge($a,$b,$c));
This produces:
array(9) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
[4]=>
string(1) "e"
[5]=>
string(1) "f"
[6]=>
string(1) "g"
[7]=>
string(1) "h"
[8]=>
string(1) "i"
}
However I want:
array(9) {
[0]=>
string(1) "a"
[1]=>
string(1) "d"
[2]=>
string(1) "g"
[3]=>
string(1) "b"
[4]=>
string(1) "e"
[5]=>
string(1) "h"
[6]=>
string(1) "c"
[7]=>
string(1) "f"
[8]=>
string(1) "i"
}
Therfore I wrote my own - tested an working - function:
function array_zip(...$arrays) {
$res = array();
while(true) {
$check_finish = true;
foreach($arrays as $array) {
if(!empty($array)) {
$check_finish = false;
}
}
if($check_finish) {
break;
} else {
foreach($arrays as $key => $array) {
if(!empty($array)) {
array_push($res,array_shift($array));
$arrays[$key] = $array;
}
}
}
}
return $res;
}
However is there a native PHP function to merge arrays like this (maybe more performant)? And is there a native PHP function for this purpose which preserves keys but keeps the order? Did not find sth :-/