2015-09-07 50 views
0

我的sql爲每個國家保存一個編號。現在想要顯示數組中的國家/地區名稱。替換國名錶格編號

這裏的問題是:如果我的國家號碼是11. str_replace顯示'1' => 'Afghanistan',兩次。未顯示11沒有任何一個國家'11' => 'Armenia',

我的代碼:

function mycountry($text){ 
    $toReplace = array(
    '1' => 'Afghanistan', 
    '7' => 'Anguilla', 
    '8' => 'Antarctica', 
    '9' => 'Antigua and Barbuda', 
    '10' => 'Argentina', 
    '11' => 'Armenia' 
    ); 

    $replacement = array(
    '1' => 'Afghanistan', 
    '7' => 'Anguilla', 
    '8' => 'Antarctica', 
    '9' => 'Antigua and Barbuda', 
    '10' => 'Argentina', 
    '11' => 'Armenia' 
    ); 
return str_replace($toReplace,$replacement,$text); 
//return preg_replace('/$toReplace/','$replacement',$text); 
} 


// Sql query select user country 
$country = 11; 
echo ''.mycountry($country).''; 

html display : AfghanistanAfghanistan 

回答

1

在陣列鍵刪除引號:

$toReplace = array(
1 => 'Afghanistan', 
7 => 'Anguilla', 
8 => 'Antarctica', 
9 => 'Antigua and Barbuda', 
10 => 'Argentina', 
11 => 'Armenia' 
); 

和使用任何陣列通俗易懂作爲字典