php - 为什么以 null 作为回调的 array_map() 创建一个 "array of arrays"?

标签 php arrays specifications array-map

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

Example #4 Creating an array of arrays

<?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);
?>

The above example will output:

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
        )

)

If the array argument contains string keys then the returned array will contain string keys if and only if exactly one array is passed. If more than one argument is passed then the returned array always has integer keys.

(try it out)

但仅此而已。没有更多的解释。我明白,这与

$d = array_map(function() { return func_get_args(); }, $a, $b, $c);

但为什么会有人希望或期望这是默认行为?它之所以这样工作,是否有技术原因,比如实现的副作用?或者这只是一个随机的“让这个函数再做一件事”的决定(看着你,array_multisort())?

最佳答案

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

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

$d = array_map('array', $a, $b, $c);

关于php - 为什么以 null 作为回调的 array_map() 创建一个 "array of arrays"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31592503/

相关文章:

css - 在 CSS 中更改显示属性的短语内容

url - URI 查询中什么是有效的,什么是无效的?

php - 热门评论 sql查询

c++在构造函数中传递数组而不在其他地方定义它们

javascript - 在 JavaScript 中,如何检查数组是否有重复的多个值?

php - 选择多个将一个单词替换为数组中的每个值

ruby-on-rails - Ruby 的 ERB 格式 "officially"在哪里定义的?

php - 将链接添加到 wordpress 短代码中

PHP切换问题

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源