我需要在关联数组中搜索和替换。
例如:
$user = "user1"; // I've updated this
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" ) ;
我想替换search1
search4
。我怎样才能做到这一点?
更新:我忘了提到数组有几个search1
值,我只想更改key is == $user
的值。很抱歉没有提到这个。
答案 0 :(得分:6)
$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1') $myarray[$key] = 'search4';
}
答案 1 :(得分:2)
有一个功能:array_map()。
// Using a lamba function, PHP 5.3 required
$newarray = array_map(
function($v) { if ($v == 'search1') $v = 'search4'; return $v; },
$myarray
);
如果您不想使用lambda函数,请定义一个普通函数或方法并回调它。
答案 2 :(得分:2)
$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" );
foreach($myarray as $key => $val)
{
if ($val == 'search1' and $key == $user )
{
$myarray[$key] = 'search4';
break;
}
}
print_r($myarray);
打印:
Array
(
[user1] => search4
[user2] => search2
[user3] => search1
)
答案 3 :(得分:2)
为什么不做呢
if (isset($myarray[$user])) $myarray[$user] = 'search4';
答案 4 :(得分:0)
$originalArray = array( "user1" => "search1" , "user2" => "search2" );
$pattern = 'search1';
$replace = 'search4';
$replacedArray = preg_replace( '/'.$pattern.'/' , $replace , $originalArray );
修复评论中提到的风险,以回应this solution
答案 5 :(得分:0)
由于帖子更新了,我有机会睡觉,我意识到我的回答是愚蠢的。如果你有一个给定的键,你需要改变它的值,为什么要遍历整个数组呢?
$user = 'user1';
$search = 'search1';
$replace = 'search4';
$array = array('user1' => 'search1', 'user2' => 'search2');
if (isset($array[$user]) && $search === $array[$user]) $array[$user] = $replace;
与@ Joseph的方法类似(几乎相同),但有一些调整:
$user = 'user1';
$array = array("user1" => "search1", "user2" => "search2" );
foreach($array as $key => &$value) {
if ($key === $user) {
$value = 'search4';
break; // Stop iterating after key has been found
}
}
通过引用传递是在foreach
内编辑的更好方法,可以说更快。
答案 6 :(得分:0)
在关联数组或数字内搜索和替换 替换任何关联数组中的值,数组可以是任何深度
function array_value_replace($maybe_array, $replace_from, $replace_to) {
if (!empty($maybe_array)) {
if (is_array($maybe_array)) {
foreach ($maybe_array as $key => $value) {
$maybe_array[$key] = array_value_replace($value, $replace_from, $replace_to);
}
} else {
if(is_string($maybe_array)){
$maybe_array = str_replace($replace_from, $replace_to, $maybe_array);
}
}
}
return $maybe_array;
}
答案 7 :(得分:0)
如果您想要特定的密钥,那么您只需添加以前的ans中的密钥条件。
$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1' && $key == $user) $myarray[$key] = 'search4';
}
答案 8 :(得分:-1)
使用str_replace应该可以工作:
$myarray = array("user1" => "search1", "user2" => "search2" ) ;
$newArray = str_replace('search1', 'search4', $myarray);
答案 9 :(得分:-1)
继Joseph的回答后,使用preg_replace可以让您在其他情况下使用该代码:
function pregReplaceInArray($pattern,$replacement,$array) {
foreach ($array as $key => $value) {
$array[$key] = preg_replace($pattern,$replacement,$value);
}
return $array;
}