【问题标题】:How to use array_combine along with str_replace in PHP如何在 PHP 中使用 array_combine 和 str_replace
【发布时间】:2015-06-29 14:33:35
【问题描述】:

我在 php 中做一些数组合并。但是,在将一个数组的键组合/映射到另一个数组的值时,我想在要组合的数组的值中进行一些字符串替换。如何在 php 中使用 str_replacearray_combine大部分没有forloop

例如:

$a1 = array("35","37","43");
$a2 = array("Testing's", "testing's", "tessting's");

普通组合如下所示,(即)在组合时删除那些字符串中的'

$a3 = array_combine($a1, $a2);

我想要的输出如下,

array(
    35 => "Testing",
    37 => "testing",
    43 => "tessting"
)

【问题讨论】:

    标签: php arrays multidimensional-array replace str-replace


    【解决方案1】:

    然后在组合它们之后,您可以在结果数组上使用array_map

    $a3 = array_map(function($e){
        return str_replace("'s", '', $e);
    }, array_combine($a1, $a2)); // anonymous function PHP 5.4 or greater
    

    【讨论】:

    • 在 php 中解析这些数据时,如何从 csv 文件数据中解析单引号、双引号和其他字符?
    【解决方案2】:

    你可以这样做:

    function cust_replace($n)
        {
            return  str_replace("'s","",$n);
        }
        $a1 = array("35","37","43");
        $a2 = array("Testing's", "testing's", "tessting's");
        $a3 = array_map("cust_replace",array_combine($a1, $a2));
        print_r($a3);
    

    如果你想让它更通用,你可以向 cust_replace 添加另一个参数——你要替换的“针”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多