PHP array_map修剪+参数 [英] PHP array_map trim + parameters

查看:98
本文介绍了PHP array_map修剪+参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 array_map 修剪所有数组值,但是我需要传递第三个参数,因为我不仅需要修剪空格,而且要传递第三个参数。 基本上,我想修剪空格,单引号和双引号的所有数组值。

I'm using array_map to trim all my array values but I need to pass a third parameter because I need to more than just trim whitespaces so I'm passing in a third parameter. Basically I want to trim all array values of whitespaces, single quotes, and double quotes.

我在创建函数的实用程序类中看起来像这样:

I have a utility class where I created the function and it looks like this:

public function convertToArray($string, $trim = false) {
    $split = explode(",", $string);

    if($trim) {
        $split = array_map("trim", $split, array(" '\""));
    }

    return $split;
}

以某种方式我无法完成这项工作但是,即使遵循答案在这里

Somehow I can't make this work though. I can still see double quotes in the result even though I followed the answer here.

我什至尝试过

if($trim) {
    $split = array_map("trim", $split);
    $split = array_map("trim", $split, array("'"));
    $split = array_map("trim", $split, array('"'));
}

但我仍然得到相同的结果。

but I still get the same result.

推荐答案

array_map 采用仅包含一个参数的函数。如果要使用 trim()映射数组,且后续参数与默认参数不同,则必须使用匿名函数将其包装:

array_map takes a function that takes only one parameter. If you want to map your array with trim() with subsequent parameters different from the default ones, you have to wrap it with an anonymous function:

$split = array_map(function($item) {
    return trim($item, ' \'"');
}, $split);

这篇关于PHP array_map修剪+参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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