在关联数组内搜索和替换
我需要在关联数组内搜索和替换。
例如:
$user = "user1"; // I've updated this
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" ) ;
我想将 search1
替换为 search4
。我怎样才能实现这个目标?
更新:我忘记提及该数组有多个 search1
值,我只想更改 key == $user
处的值。抱歉没有早点提到这一点。
I need to search and replace inside an associative array.
ex:
$user = "user1"; // I've updated this
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" ) ;
I want to replace search1
for search4
. How can I achieve this?
UPDATE: I forgot to mention that the array has several search1
values and I just want to change the value where the key is == $user
. Sorry for not mention this earlier.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
更新
自从帖子更新后,我有机会睡一觉,我意识到我的回答很愚蠢。如果您有给定的键并且需要更改它的值,为什么要迭代整个数组呢?
与 @Joseph 的方法类似(几乎相同),但有一些调整:
通过引用传递是在
foreach
内编辑的更好方法,并且可以说更快。Updated
Since the post was updated, and I have had chance to get some sleep, I realized my answer was stupid. If you have a given key and you need to change it's value, why iterate over the whole array?
Similar to @Joseph's method (pretty much the same), but with a few tweaks:
Passing by reference is a nicer way to edit inside
foreach
, and is arguably quicker.在关联数组或数字中搜索和替换
替换任何关联数组中的值,并且数组可以是任何深度
Search and replace inside an associative array or numeric
Replace value in any associative array and array can be any deep
如果您想要特定的密钥,那么您只需在前面的示例中添加密钥条件即可。
if you want for particular key then you just add condition for key in previous ans like.
使用 str_replace 应该可以:
Using str_replace should work:
根据约瑟夫的回答,使用 preg_replace 可能会启用您可以在其他情况下使用该代码:
Following on from Joseph's answer, using preg_replace may enable you to use the code in other situations:
有一个函数可以实现此目的:array_map()。
如果您不想使用 lambda 函数,请定义一个普通函数或方法并对其进行回调。
There's a function for this : array_map().
If you don't want to use a lambda function, define a normal function or method and callback to it.
为什么不直接做
Why not just do
印刷:
Prints:
修复了响应此解决方案
Fixes the risk mentioned in comment in response to this solution