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

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

问题描述

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

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.

推荐答案

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

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:

Tomas的编辑:该代码无法正常工作,已更正:

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天全站免登陆