为什么带有null作为回调的array_map()会创建一个"数组数组"?

Fab*_*ler 7 php arrays specifications array-map

今天我学习了array_map()PHP的一个特例,在文档中作为旁注提到:

Example#4创建一个数组数组

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>
Run Code Online (Sandbox Code Playgroud)

上面的例子将输出:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)
Run Code Online (Sandbox Code Playgroud)

如果数组参数包含字符串键,则当且仅当传递了一个数组时,返回的数组将包含字符串键.如果传递了多个参数,则返回的数组始终具有整数键.

(试试看)

但就是这样.没有更多的解释.我明白,这和我一样

$d = array_map(function() { return func_get_args(); }, $a, $b, $c);
Run Code Online (Sandbox Code Playgroud)

但是为什么有人想要或期望这是默认行为?有没有技术上的原因,为什么它的工作原理,如实施的副作用?或者这只是一个随机的"让这个功能再做一件事"的决定(看着你array_multisort())?

Bar*_*mar 5

这似乎是 _array_map_ 中的特殊情况,但仅在该示例中记录。通常不允许NULLcall_user_func()作为回调(如果您尝试将其与它一起使用,则会报告错误),但在 _array_map()_ 中允许使用 NULL。它认为NULL它应该简单地创建一个参数数组。

这很有用,因为array作为回调也是无效的,因为它是语言构造,而不是函数。所以你不能写:

$d = array_map('array', $a, $b, $c);
Run Code Online (Sandbox Code Playgroud)