Rob
Rob

Reputation: 39

PHP get a string into a associative array

I've got a variable going like this(in the original list there no whitespace): http://www.iso.org/iso/list-en1-semic-3.txt

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

(going on and on in the same order)

I like to put this in a array going like this:

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

I've try to use php explode but that doesn't work, my knowledge is to basic to get it right. Who can help?

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

Upvotes: 0

Views: 1605

Answers (3)

Karoly Horvath
Karoly Horvath

Reputation: 96266

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

Note: remove extra empty lines from $country or check for empty lines.

Upvotes: 0

adlawson
adlawson

Reputation: 6431

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

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

Upvotes: 1

cwallenpoole
cwallenpoole

Reputation: 82048

This will get you where you're going:

$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 ];
    }
}

Upvotes: 2

Related Questions