如何在PHP中使用带array_map(...)的数组数组?

时间:2016-09-20 16:47:17

标签: php ellipsis variadic variadic-functions

PHP函数array_map(...)期望回调作为第一个参数(或creating an array of arraysnull)和可变数量的数组参数,例如:

$foo => array_map(null, $bar, $buz);

现在我有一个案例,我需要向array_map(...)传递可变数量的数组。我不能对此进行硬编码,因为array_map(...)输入的数组是动态生成的。

function performSomeLogicAndGetArgumentsForMyFunction() {
    ...
    return ['bar' => [...], 'buz' => [...]];
}
$foo = array_map(null, performSomeLogicAndGetArgumentsForMyFunction());

它不会以这种方式工作,因为array_map(...)期望可变数量的数组而不是数组数组

有解决方案吗? 如何保持调用的灵活性并将可变数量的参数传递给array_map(...)(它也适用于我无法操作的所有其他可变参数函数。)

2 个答案:

答案 0 :(得分:0)

您正在返回一个数组数组,并且您希望映射这些数组的最内层。您可以使用argument unpacking

function say($n, $m) {
    return "The number $n is called $m in Spanish";
}
function arrays() {
    return [
        [ 1, 2, 3 ],
        [ 'uno', 'dos', 'tres' ],
    ];
}
print_r(
    array_map('say', ...arrays())
);

See it online at 3v4l.org.

或者,您可以使用RFC中提到的call_user_func_array以可衡量的运行时费用:

print_r(
    call_user_func_array(
        'array_map',
        array_merge(array ('say'), arrays())
    )
);

See it online at 3v4l.org.

这些模式中的任何一种都可以实现可变形式的常用方法。例如,要模拟vsprintf,可以使用:

sprintf('%s %s', ...['Hello', 'World']);
call_user_func_array('sprintf', array_merge(['%s, %s'], ['Hello', 'World']));

答案 1 :(得分:-2)

作为最后的手段,请使用eval

//build you array of array variable names with the dynamic content coming in.
$arrays = ['$foo', '$bar', '$baz'];

$str = implode(', ', $arrays);
eval("\$map = array_map(null, $str);");

print_r($map);

请注意永远不要将未经过清理的输入发送到eval。

See it working