doulang9521 2015-07-23 16:00
浏览 63
已采纳

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

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

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)

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

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

  • 写回答

1条回答 默认 最新

  • dsc862009 2015-07-24 16:16
    关注

    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.

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题