从整个关联数组项中删除特定字符串

时间:2016-06-10 04:57:50

标签: php arrays associative-array

我有一个关联数组。我想从整个数组项中删除特定的字符串。这是我的数组的结构:

Array
(
    [50808] => Array
        (
            [quantity] => 2
            [name] => asv (test)
        )

    [50809] => Array
        (
            [quantity] => 2
            [name] => 37 (test)
        )

    [50810] => Array
        (
            [quantity] => 3
            [name] => 38 (test)
        )

)

我希望输出:

Array
(
    [50808] => Array
        (
            [quantity] => 2
            [name] => asv
        )

    [50809] => Array
        (
            [quantity] => 2
            [name] => 37
        )

    [50810] => Array
        (
            [quantity] => 3
            [name] => 38
        )

)

我知道它非常简单的使用循环,但我想在没有循环的情况下这样做。

1 个答案:

答案 0 :(得分:1)

使用array_map功能

<?php
$array = Array
(
    '50808' => Array
        (
            'quantity' => 2,
            'name' => 'asv (test)',
        ),

    '50809' => Array
        (
            'quantity' => 2,
            'name' => '37 (test)'
        ),

    '50810' => Array
        (
            'quantity' => 3,
            'name' => '38 (test)'
        )

);

echo '<pre>';

$new_array = array_map(function($val){
    $val['name'] = trim(str_replace('(test)', '', $val['name']));
    return $val;
}, $array);

print_r($new_array);

<强>输出:

Array
(
    [50808] => Array
        (
            [quantity] => 2
            [name] => asv
        )

    [50809] => Array
        (
            [quantity] => 2
            [name] => 37
        )

    [50810] => Array
        (
            [quantity] => 3
            [name] => 38
        )

)

另一种方法可以是array_walk功能:

array_walk($array, function(&$val){
    $val['name'] = trim(str_replace('(test)', '', $val['name']));
});

print_r($array); //out put: desired output