将函数应用于数组的简单方法 [英] Easy way to apply a function to an array
问题描述
我知道array_walk()
和array_map()
.但是,当像这样(在旧项目中)使用前者时,它失败了
array_walk($_POST, 'mysql_real_escape_string');
<块引用>
警告:mysql_real_escape_string()期望参数 2 是资源,给定的字符串.
所以我选择了这个稍微丑一点的版本
foreach($_POST as $key => $value) {$_POST[$key] = mysql_real_escape_string($value);}
那么为什么第一种方法不起作用?将数组的值映射到函数的最佳方法是什么?
传递给 array_walk
预计接受两个参数,一个是值,一个是键:
通常,funcname 接受两个参数.array 参数的值是第一个,键/索引是第二个.
但是 mysql_real_escape_string
期望第二个参数是一个资源.这就是您收到该错误的原因.
使用 array_map
代替,它只获取每个项目的值并传递它到给定的回调函数:
array_map('mysql_real_escape_string', $_POST);
第二个参数将被省略,因此使用最后打开的连接.
如果需要传递第二个参数,则需要将函数调用包装在另一个函数中,例如匿名函数:
array_map(function($string) use ($link) { return mysql_real_escape_string($string, $link); }, $_POST);
I am aware of array_walk()
and array_map()
. However when using the former like so (on an old project) it failed
array_walk($_POST, 'mysql_real_escape_string');
Warning: mysql_real_escape_string() expects parameter 2 to be resource, string given.
So I went with this slightly more ugly version
foreach($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
So why didn't the first way work? What is the best way to map values of an array to a function?
The callback function passed to array_walk
is expected to accept two parameters, one for the value and one for the key:
Typically, funcname takes on two parameters. The array parameter's value being the first, and the key/index second.
But mysql_real_escape_string
expects the second parameter to be a resource. That’s why you’re getting that error.
Use array_map
instead, it only takes the value of each item and passes it to the given callback function:
array_map('mysql_real_escape_string', $_POST);
The second parameter will be omitted and so the last opened connection is used.
If you need to pass the second parameter, you need to wrap the function call in another function, e.g. an anonymous function:
array_map(function($string) use ($link) { return mysql_real_escape_string($string, $link); }, $_POST);
这篇关于将函数应用于数组的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!