2011-07-13 91 views
0

我有一個變量會像這樣(在原始列表中有沒有空格): http://www.iso.org/iso/list-en1-semic-3.txtPHP得到一個字符串轉換爲關聯數組

$country =" 
ÅLAND ISLANDS;AX 
ALBANIA;AL 
ALGERIA;DZ 
"; 

(以相同的順序滔滔不絕地)

我喜歡把這個陣列會像這樣:

array: [Åland Islands] ==> AX 
     [Albania] ==> AL 
     [Algeria] ==> DZ 

我已經嘗試使用PHP的爆炸,但還是不行,我的知識是基本得到它的權利。誰可以幫忙?

print_r(explode(';', $country)); 
+0

首先按行(「\ n」)爆炸 –

回答

1
$result = array(); 
$lines = explode(PHP_EOL, $country); 

foreach ($lines as $line) { 
    $line = explode(';', $line); 
    $result[array_shift($line)] = array_shift($line); 
} 
+0

這個伎倆謝謝你! – Rob

2

這將讓你你要去的地方:

$output = array(); 
// break it line-by-line 
$lines = explode('\n', $country); 
// iterate through the lines. 
foreach($lines as $line) 
{ 
    // just make sure that the line's whitespace is cleared away 
    $line = trim($line); 
    if($line) 
    { 
     // break the line at the semi-colon 
     $pieces = explode(";", $line); 
     // the first piece now serves as the index. 
     // The second piece as the value. 
     $output[ $pieces[ 0 ] ] = $pieces[ 1 ]; 
    } 
} 
+0

呵呵,快點! +1修剪雖然;) – adlawson

0
$a = explode("\n", $country); 
$result = array(); 
foreach($a as $line) { 
    list($x,$y) = explode(";", $line); 
    $result[$x] = $y; 
} 

注:請從$國家額外的空行或檢查空行。

+0

在第四行 – Rob

+0

中給出了「注意:未定義偏移:1」,這就是爲什麼我寫空行註釋... –