Aci*_*don 7 php function array-filter
这里的PHP函数允许以输出数组的方式合并任意N个不同长度的数组,顺序如下Array1[0],Array2[0],..,ArrayN[0],Array1[1],Array2[1],..,ArrayN[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
Run Code Online (Sandbox Code Playgroud)
虽然我理解这个示例中的每个内置函数都是自己做的,但我不能完全理解它在这个函数中如何一起工作,尽管包括解释注释......
有人可以帮我分手吗?这个功能很好用,它让我疯狂,我不明白它是如何工作的......
PS:此函数取自将多个数组交错为单个数组问题.
小智 3
数组$a、$b和$c分别有 10、6 和 2 个元素。
$a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$b = ['a', 'b', 'c', 'd', 'e', 'f'];
$c = ['A', 'B'];
Run Code Online (Sandbox Code Playgroud)
当您将数组作为array_zip_merge()函数的参数提供时,请查看for循环。将func_get_args()设置$args提供的所有参数。for在第一次循环运行开始时,
$args = [$a, $b, $c];
count($args) = 3;
Run Code Online (Sandbox Code Playgroud)
在foreach循环中array_shift,将返回每个数组的第一个元素,结果$output如下
$output = [1, 'a', 'A'];
Run Code Online (Sandbox Code Playgroud)
数组现在看起来像,
$a = [2, 3, 4, 5, 6, 7, 8, 9, 10];
$b = ['b', 'c', 'd', 'e', 'f'];
$c = ['B'];
Run Code Online (Sandbox Code Playgroud)
for在第一个循环结束时,该array_filter函数将测试是否有任何数组为空并将其从 中删除$args。第二次运行时会发生同样的事情,到第二次循环结束时for,变量将如下所示
$a = [3, 4, 5, 6, 7, 8, 9, 10];
$b = ['c', 'd', 'e', 'f'];
$c = [];
$output = $output = [1, 'a', 'A', 2, 'b', 'B'];
//because $c is empty array_filter() removes it from $args
$args = [$a, $b];
Run Code Online (Sandbox Code Playgroud)
for因此,在循环的第三次迭代中将count($args)返回2。当 的最后一个元素$b已被 删除时array_shift将count($args)返回1。迭代将继续,直到所有数组为空