为什么将null为回调的array_map()创建“数组数组”? [英] Why does array_map() with null as callback create an "array of arrays"?

查看:123
本文介绍了为什么将null为回调的array_map()创建“数组数组”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我了解了PHP中 array_map()的一种特殊情况,在文档的旁注中提到了这种情况:

Today I learned about a special case of array_map() in PHP, which is mentioned as a side note in the documentation:


示例#4创建数组



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

上面的示例将输出:

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
        )

)

如果array参数包含字符串键,则返回数组
wi仅当仅传递了一个数组时,ll才会包含字符串键。
如果传递了多个参数,则返回的数组将始终具有
个整数键。

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.

(尝试一下)

但是就是这样。没有更多的解释。我了解,这与

But that's it. No more explanation. I understand, that this does the same as

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

但是为什么有人会希望或期望这是默认行为呢?是否有技术上的原因使它像实现一样产生副作用?还是这只是一个随机的让我们让这个功能做更多的事情的决定(看着你, array_multisort())?

But why would anybody want or expect this as default behavior? Is there a technical reason why it works like that, like a side effect from the implemtation? Or was this just a random "let's make this function do one more thing" decision (looking at you, array_multisort())?

推荐答案

这在_array_map_中似乎是特例,但仅在该示例中进行了说明。通常不允许将 NULL 用作回调(如果尝试与 call_user_func()一起使用,则会报告错误),但是_array_map中允许()_。它将 NULL 视为意味着应仅创建参数数组。

This appears to be a special case in _array_map_, but it's only documented in that example. NULL is not normally allowed as a callback (if you try to use it with call_user_func() it reports an error), but it's allowed in _array_map()_. It treats NULL as meaning that it should simply create an array of the arguments.

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

This is useful because array is also not valid as a callback, because it's language construct, not a function. So you can't write:

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

这篇关于为什么将null为回调的array_map()创建“数组数组”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆