我需要将多个数组合并为一个数组。描述我正在寻找的内容的最佳方式是将数组“交错”到一个数组中。
例如,从数组 #1 中取出第一项并附加到最终数组。从数组 #2 中获取第一项并附加到最终数组。从数组 #1 中获取项目二并追加...等等。
最终的数组看起来像这样:
数组#1.元素#1 数组#2.元素#1 . . .
“踢球者”是各个数组可以有不同的长度。
有没有更好的数据结构可以使用?
最佳答案
例如,
function array_zip_merge() {
$output = array();
// The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
for ($args = func_get_args(); count($args); $args = array_filter($args)) {
// &$arg allows array_shift() to change the original.
foreach ($args as &$arg) {
$output[] = array_shift($arg);
}
}
return $output;
}
// test
$a = range(1, 10);
$b = range('a', 'f');
$c = range('A', 'B');
echo implode('', array_zip_merge($a, $b, $c)); // prints 1aA2bB3c4d5e6f78910
关于php - 将多个数组交织成一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1860490/