如何在 PHP 中使用带有 array_map(...) 的数组? [英] How to use an array of arrays with array_map(...) in PHP?
问题描述
PHP 函数 array_map(...)
期望回调作为第一个参数(或 null
对于 创建数组数组) 和可变数量的数组参数,例如:
The PHP function array_map(...)
expects a callback as first parameter (or null
for creating an array of arrays) and a variable number of array arguments, e.g.:
$foo => array_map(null, $bar, $buz);
现在我有一个案例,我需要将可变数量的数组传递给 array_map(...)
.我无法对此进行硬编码,因为 array_map(...)
的输入数组是动态生成的.
Now I have a case, where I need to pass to array_map(...)
a variable number of arrays. I cannot hard-code this, since the arrays for the array_map(...)
's input are generated dynamically.
function performSomeLogicAndGetArgumentsForMyFunction() {
...
return ['bar' => [...], 'buz' => [...]];
}
$foo = array_map(null, performSomeLogicAndGetArgumentsForMyFunction());
它不能这样工作,因为 array_map(...)
需要 一个可变数量的数组 而不是 一个数组数组.
It doesn't work this way, since array_map(...)
expects a variable number of array and not an array of arrays.
有没有办法解决这个问题?如何保持调用的灵活性并将可变数量的参数传递给 array_map(...)
?(它也适用于我无法操作的所有其他可变参数函数.)
Is there a solution for this? How can I keep the call flexible and pass a variable number of arguments to the array_map(...)
? (It also applies to every other variadic function I cannot manipulate.)
推荐答案
您要返回一个数组数组,并且想要映射这些数组的最里面.您可以使用参数解包:
You're returning an array of arrays, and you want to map over the innermost of those arrays. You can use argument unpacking for this:
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())
);
或者,您可以使用 RFC 中提到的 call_user_func_array
以可衡量的运行时间成本:
Alternatively, you could use call_user_func_array
as mentioned in the RFC at a measurable run-time cost:
print_r(
call_user_func_array(
'array_map',
array_merge(array ('say'), arrays())
)
);
这些模式中的任何一个都可以实现常见方法的可变参数形式.例如,要模拟 vsprintf
可以使用:
Either of these patterns can implement variadic forms of common methods. For example, to emulate vsprintf
one can use:
sprintf('%s %s', ...['Hello', 'World']);
call_user_func_array('sprintf', array_merge(['%s, %s'], ['Hello', 'World']));
这篇关于如何在 PHP 中使用带有 array_map(...) 的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!