一个函数应用到一个数组的简便方法 [英] Easy way to apply a function to an array

查看:101
本文介绍了一个函数应用到一个数组的简便方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道的array_walk() array_map()。但是使用(在一个旧的项目),像这样前,当它失败。

  array_walk($ _ POST,'mysql_real_escape_string');


  

警告:mysql_real_escape_string()
  预计参数2是资源,
  串给出。


所以,我这个稍微难看版本了。

 的foreach($ _ POST为$关键=> $值){
    $ _ POST [$关键] = mysql_real_escape_string($值);
}

那么,为什么没有第一种方式工作?什么是一个数组的值映射到一个函数的最佳方式?


解决方案

传递给 array_walk 预计接受两个参数,一个用于值和一个用于关键:


  

一般情况下,的 funcname的的接受两个参数。在阵列的参数的值作为第一个,键/索引秒。


mysql_real_escape_string 预计,第二个参数是一个资源。这就是为什么你得到这个错误。

使用 array_map 代替,只需要每个项目,并传递价值它给定的回调函数:

  array_map('mysql_real_escape_string',$ _ POST);

第二个参数将被省略,所以最后一个打开的连接使用。

如果你需要传递的第二个参数,你需要用另外一个函数的函数调用,例如一个匿名函数

  array_map(函数($字符串)使用($链接){返回mysql_real_escape_string($字符串,$链接);},$ _ 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屋!

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