2014-03-05 85 views
1

我有一個這樣的數組:在multidimensionnal陣列替換字符串

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

不應該它是'if($ key ['city'] ==「NEW-YORK」){'? –

+0

尋找'php array_merge' – Lekhnath

回答

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); 
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; 
} 
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']); 
}