There are multiple ways to do this I'm sure. I have an array that looks like this:
我确信有多种方法可以做到这一点。我有一个看起来像这样的数组:
$map=array(
'ABC'=>'first_three',
'DEF'=>'second_three',
'GHI'=>'third_three'
)
$info=array(
array('x','XXABCXXXX','x','x','x'),
array('x','XXXDEFXXXX','x','x','x'),
array('x','XXXXXXXXXX','x','x','x'),
array('x','XXXXXXXABC','x','x','x'),
array('x','XXXXXXXXXX','x','x','x')
)
I want to do a find/replace so that the 2nd string in the array will be compared to the keys in $map and if any are found, they'll replace the key with whatever was in the $map.
我想进行查找/替换,以便将数组中的第二个字符串与$ map中的键进行比较,如果找到任何键,它们将用$ map中的任何内容替换键。
array('x','XXfirst_threeXXXX','x','x','x')
I want to loop through $info so:
我想遍历$ info所以:
foreach ($info as $i){
[something with $i[1] and $map]
}
What's the most efficient way to do this? Does it use "in_array"?
最有效的方法是什么?它使用“in_array”吗?
2 个解决方案
#1
Need $i
referenced with &
to use this way:
需要$ i引用&以这种方式使用:
foreach ($info as &$i){
$i[1] = str_replace(array_keys($map), $map, $i[1]);
}
#2
foreach($info as $key => $i) {
foreach($map as $k => $v) {
// replace the key $k ("ABC") with the value $v ("first_three") in the 2nd element of $info, for each $key
$info[$key][1] = str_replace($k, $v, $info[$key][1]);
}
}
#1
Need $i
referenced with &
to use this way:
需要$ i引用&以这种方式使用:
foreach ($info as &$i){
$i[1] = str_replace(array_keys($map), $map, $i[1]);
}
#2
foreach($info as $key => $i) {
foreach($map as $k => $v) {
// replace the key $k ("ABC") with the value $v ("first_three") in the 2nd element of $info, for each $key
$info[$key][1] = str_replace($k, $v, $info[$key][1]);
}
}