在 PHP 数组中搜索和替换值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8668826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
search and replace value in PHP array
提问by TMS
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.
请注意,此功能只会进行一次替换。我正在寻找类似替换单个事件的现有解决方案,以及替换所有事件的现有解决方案。
采纳答案by Deept Raghav
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
)
);
回答by outis
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:
要使用值数组 => 替换来替换多次出现的多个值:
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 开发人员没有太多理由创建标准函数来执行任务。并不是说创建这样的函数没有意义,如果您发现自己经常需要它。
回答by Prasad Rajapaksha
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!
干杯!
回答by BurninLeo
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];
}
}
回答by user3396065
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);
回答by Douglas Comim
$ar[array_search('green', $ar)] = 'value';
$ar[array_search('green', $ar)] = 'value';
回答by Dan - See Green
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.
我不是说这是最有效或最优雅的,而是说它很好很简单。
回答by waltzofpearls
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
回答by Muthu Krishnan
<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] = '苹果'; // 用“苹果”替换“绿色”