在 PHP 数组中搜索和替换值 [英] search and replace value in PHP array

查看:52
本文介绍了在 PHP 数组中搜索和替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

注意这个函数只会做一次替换.我正在寻找类似替换单个事件的现有解决方案,以及替换所有事件的现有解决方案.

解决方案

虽然没有与示例代码等效的功能,但您可以使用 array_keys(带有可选的搜索值参数),array_fillarray_replace 来实现同样的事情:>

由 Tomas 编辑:代码不起作用,已更正:

$ar = array_replace($ar,array_fill_keys(array_keys($ar, $value),$替换));

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:

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.

解决方案

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:

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

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

这篇关于在 PHP 数组中搜索和替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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