我有一个这样的数组:
Array
(
[0] => Array
(
[objectid] => 197
[adresse] => D554
[city] => NEW-YORK
[lat] => 12,545484654687
[long] => 12,545484654687
)
[1] => Array
(
[objectid] => 198
[adresse] => D556
[city] => WASHINGTON
[lat] => 12,545484654687
[long] => 12,545484654687
)
...
...
)
我想用0,1,2 ......等标识符更改城市名称。
实际上,我是通过这段代码完成的:
foreach ($big_array as $key => $value){
if ($value['city'] == "NEW-YORK"){
$big_array[$key] = str_replace("NEW-YORK", 0, $value);
} elseif($value['city'] == "WASHINGTON") {
$big_array[$key] = str_replace("WASHINGTON", 1, $value);
} etc...
}
我认为这不是最好的方法,我有很多城市。 是否可以定义如下数组:
$replacements = array(
"NEW-YORK" => 0,
"WASHINGTON" => 1,
etc...
)
并使用函数简单地执行更改?
答案 0 :(得分:1)
如果通过引用
传递数组,则可以直接替换数组的值foreach ($big_array as &$value) {
$city = $value['city'];
// for cities that we don't have a replacement
if (! isset($replacements[$city])) {
continue;
}
$value['city'] = $replacements[$city];
}
// just to be sure we don't keep any reference to the $value variable
unset($value);
答案 1 :(得分:0)
具有$replacements
数组的逻辑应该类似于:
foreach ($big_array as $key => $value)
{
if (!isset($replacements[$value['city']])
{
echo "Could not find city '".$value['city']."' in replacements array, skipping";
continue;
}
$value['city'] = $replacements[$value['city']];
$big_array[$key] = $value;
}
答案 2 :(得分:0)
$find = array(0, 1, etc...);
$replace = array("NEW-YORK", "WASHINGTON", ect ...);
foreach ($big_array as $key => $value){
$big_array[$key]['city'] = str_replace($find, $value['city']);
}