在PHP数组中搜索和替换值

时间:2022-03-11 22:08:14

I was looking for some standard PHP function to replace some value of an array with other, but surprisingly I haven't found any, so I have to write my own:

我正在寻找一些标准的PHP函数来替换其他的数组值,但令人惊讶的是我没有找到任何,所以我必须自己编写:

function array_replace_value(&$ar, $value, $replacement)
{
    if (($key = array_search($ar, $value)) !== FALSE) {
        $ar[$key] = $replacement;
    }
}

But I still wonder - for such an easy thing there must already be some function for it! Or maybe much easier solution than this one invented by me?

但我仍然想知道 - 对于这么简单的事情,它必须已经有了一些功能!或者可能比我发明的更容易解决方案?

Note that this function will only do one replacement. I'm looking for existing solutions that similarly replace a single occurrence, as well as those that replace all occurrences.

请注意,此功能仅执行一次替换。我正在寻找类似替换单个事件的现有解决方案,以及替换所有事件的解决方案。

8 个解决方案

#1


19  

While there isn't one function equivalent to the sample code, you can use array_keys (with the optional search value parameter), array_fill and array_replace to achieve the same thing:

虽然没有一个函数等效于示例代码,但您可以使用array_keys(使用可选的搜索值参数),array_fill和array_replace来实现相同的功能:

EDIT by Tomas: the code was not working, corrected it:

由Tomas编辑:代码无效,纠正了它:

$ar = array_replace($ar,
    array_fill_keys(
        array_keys($ar, $value),
        $replacement
    )
);

#2


22  

Instead of a function that only replaces occurrences of one value in an array, there's the more general array_map:

而不是仅替换数组中一个值的出现的函数,而是更通用的array_map:

array_map(function ($v) use ($value, $replacement) {
    return $v == $value ? $replacement : $v;
}, $arr);

To replace multiple occurrences of multiple values using array of value => replacement:

要使用value => replacement数组替换多个值的多次出现:

array_map(function ($v) use ($replacement) {
    return isset($replacement[$v]) ? $replacement[$v] : $v;
}, $arr);

To replace a single occurrence of one value, you'd use array_search as you do. Because the implementation is so short, there isn't much reason for the PHP developers to create a standard function to perform the task. Not to say that it doesn't make sense for you to create such a function, if you find yourself needing it often.

要替换单个值的一个值,您可以像使用array_search一样。由于实现很短,因此PHP开发人员没有太多理由创建标准函数来执行任务。如果您发现自己经常需要它,那并不是说创建这样的函数没有意义。

#3


5  

Try this function.

试试这个功能。

public function recursive_array_replace ($find, $replace, $array) {
    if (!is_array($array)) {
        return str_replace($find, $replace, $array);
    }

    $newArray = [];
    foreach ($array as $key => $value) {
        $newArray[$key] = recursive_array_replace($find, $replace, $value);
    }
    return $newArray;
}

Cheers!

干杯!

#4


3  

If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.

如果性能是个问题,可以考虑不在array_map()中创建多个函数。请注意,isset()非常快,此解决方案根本不会调用任何其他函数。

$replacements = array(
    'search1' => 'replace1',
    'search2' => 'replace2',
    'search3' => 'replace3'
);
foreach ($a as $key => $value) {
    if (isset($replacements[$value])) {
        $a[$key] = $replacements[$value];
    }
}

#5


2  

What about array_walk() with callback?

带回调的array_walk()怎么样?

$array = ['*pasta', 'cola', 'pizza'];
$search = '*';
$replace = '\*';
array_walk($array,
    function (&$v) use ($search, $replace){
        $v = str_replace($search, $replace, $v);    
    }                                                                     
);  
print_r($array);

#6


0  

Based on Deept Raghav's answer, I created the follow solution that does regular expression search.

根据Deept Raghav的回答,我创建了以下解决方案,进行正则表达式搜索。

$arr = [
    'Array Element 1',
    'Array Element 2',
    'Replace Me',
    'Array Element 4',
];

$arr = array_replace(
    $arr,
    array_fill_keys(
        array_keys(
            preg_grep('/^Replace/', $arr)
        ),
        'Array Element 3'
    )
);

echo '<pre>', var_export($arr), '</pre>';

PhpFiddle: http://phpfiddle.org/lite/code/un7u-j1pt

PhpFiddle:http://phpfiddle.org/lite/code/un7u-j1pt

#7


0  

Depending whether it's the value, the key or both you want to find and replace on you could do something like this:

根据您要查找和替换的值,键或两者,您可以执行以下操作:

$array = json_decode( str_replace( $replace, $with, json_encode( $array ) ), true );

I'm not saying this is the most efficient or elegant, but nice and simple.

我不是说这是最有效或最优雅,但又好又简单。

#8


-1  

 <b>$green_key = array_search('green', $input); // returns the first key whose value is 'green'

$input[$green_key] = 'apple'; // replace 'green' with 'apple'

$ input [$ green_key] ='apple'; //用'apple'替换'green'

#1


19  

While there isn't one function equivalent to the sample code, you can use array_keys (with the optional search value parameter), array_fill and array_replace to achieve the same thing:

虽然没有一个函数等效于示例代码,但您可以使用array_keys(使用可选的搜索值参数),array_fill和array_replace来实现相同的功能:

EDIT by Tomas: the code was not working, corrected it:

由Tomas编辑:代码无效,纠正了它:

$ar = array_replace($ar,
    array_fill_keys(
        array_keys($ar, $value),
        $replacement
    )
);

#2


22  

Instead of a function that only replaces occurrences of one value in an array, there's the more general array_map:

而不是仅替换数组中一个值的出现的函数,而是更通用的array_map:

array_map(function ($v) use ($value, $replacement) {
    return $v == $value ? $replacement : $v;
}, $arr);

To replace multiple occurrences of multiple values using array of value => replacement:

要使用value => replacement数组替换多个值的多次出现:

array_map(function ($v) use ($replacement) {
    return isset($replacement[$v]) ? $replacement[$v] : $v;
}, $arr);

To replace a single occurrence of one value, you'd use array_search as you do. Because the implementation is so short, there isn't much reason for the PHP developers to create a standard function to perform the task. Not to say that it doesn't make sense for you to create such a function, if you find yourself needing it often.

要替换单个值的一个值,您可以像使用array_search一样。由于实现很短,因此PHP开发人员没有太多理由创建标准函数来执行任务。如果您发现自己经常需要它,那并不是说创建这样的函数没有意义。

#3


5  

Try this function.

试试这个功能。

public function recursive_array_replace ($find, $replace, $array) {
    if (!is_array($array)) {
        return str_replace($find, $replace, $array);
    }

    $newArray = [];
    foreach ($array as $key => $value) {
        $newArray[$key] = recursive_array_replace($find, $replace, $value);
    }
    return $newArray;
}

Cheers!

干杯!

#4


3  

If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.

如果性能是个问题,可以考虑不在array_map()中创建多个函数。请注意,isset()非常快,此解决方案根本不会调用任何其他函数。

$replacements = array(
    'search1' => 'replace1',
    'search2' => 'replace2',
    'search3' => 'replace3'
);
foreach ($a as $key => $value) {
    if (isset($replacements[$value])) {
        $a[$key] = $replacements[$value];
    }
}

#5


2  

What about array_walk() with callback?

带回调的array_walk()怎么样?

$array = ['*pasta', 'cola', 'pizza'];
$search = '*';
$replace = '\*';
array_walk($array,
    function (&$v) use ($search, $replace){
        $v = str_replace($search, $replace, $v);    
    }                                                                     
);  
print_r($array);

#6


0  

Based on Deept Raghav's answer, I created the follow solution that does regular expression search.

根据Deept Raghav的回答,我创建了以下解决方案,进行正则表达式搜索。

$arr = [
    'Array Element 1',
    'Array Element 2',
    'Replace Me',
    'Array Element 4',
];

$arr = array_replace(
    $arr,
    array_fill_keys(
        array_keys(
            preg_grep('/^Replace/', $arr)
        ),
        'Array Element 3'
    )
);

echo '<pre>', var_export($arr), '</pre>';

PhpFiddle: http://phpfiddle.org/lite/code/un7u-j1pt

PhpFiddle:http://phpfiddle.org/lite/code/un7u-j1pt

#7


0  

Depending whether it's the value, the key or both you want to find and replace on you could do something like this:

根据您要查找和替换的值,键或两者,您可以执行以下操作:

$array = json_decode( str_replace( $replace, $with, json_encode( $array ) ), true );

I'm not saying this is the most efficient or elegant, but nice and simple.

我不是说这是最有效或最优雅,但又好又简单。

#8


-1  

 <b>$green_key = array_search('green', $input); // returns the first key whose value is 'green'

$input[$green_key] = 'apple'; // replace 'green' with 'apple'

$ input [$ green_key] ='apple'; //用'apple'替换'green'