PHP将字符串转换为关联数组

时间:2011-07-13 01:59:56

标签: php associative-array

我有一个像这样的变量(在原始列表中没有空格): http://www.iso.org/iso/list-en1-semic-3.txt

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

(以相同的顺序继续)

我喜欢把它放在这样的数组中:

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

我尝试使用php爆炸,但这不起作用,我的基本知识是正确的。谁可以帮忙?

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

3 个答案:

答案 0 :(得分: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 ];
    }
}

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

注意:从$ country中删除多余的空行或检查空行。