PHP:array_merge()处于替代顺序(zip顺序)? [英] PHP: array_merge() in alternate order (zip order)?
本文介绍了PHP:array_merge()处于替代顺序(zip顺序)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个本机PHP函数来压缩合并两个数组?
Is there a native PHP function to zip merge two arrays?
看下面的例子:
$a = array("a","b","c");
$b = array("d","e","f");
$c = array("g","h","i");
var_dump(array_merge($a,$b,$c));
这将产生:
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"
}
但是我想要
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;
}
但是,有一个本机PHP函数来合并这样的数组(也许性能更高)吗?是否有用于此目的的本机PHP函数保留键但保持顺序?找不到某事:-/
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 :-/
推荐答案
没有用于此目的的PHP本机功能.但是,根据@Mark Baker的评论,实现此功能的可能性很小:
There is no PHP native function for this purpose. However according to the comment of @Mark Baker there is a short possibility to implement this:
$a = array("a","b","c");
$b = array("d","e","f");
$c = array("g","h","i");
function array_zip(...$arrays) {
return array_merge(...array_map(null, ...$arrays));
}
var_dump(array_zip($a,$b,$c));
这篇关于PHP:array_merge()处于替代顺序(zip顺序)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文