phpstringassociative-arrayexplodetext-parsing

Parse multiple lines of formatted text and generate an associative array


I am trying to get a simple array from a string.

Ej. [position] => ???? [ heading] => ??? [ pitch] => ??? [ zoom] => ???

But for some reason I get the following error:

Notice: Undefined index: heading on line 21

Here is the PHP code:

<?php
$mysql_data= 
"position: 34.032616, -118.286564|
heading: -159.50240187408838|
pitch: 0|
zoom: 2";

$pov = explode("|", $mysql_data);
foreach($pov as $key)
{
    $element = explode(": ", $key);
    $pov[ $element[0] ] = $element[1];
}
unset($element);


//Testing echoes
print_r($pov);
echo "\n";
echo $pov['heading'];
?>

Also, is there a simpler way to do this in a single go and skip foreach all together?
BTW: I do not need key's 0,1..etc, only labeled ones like 'heading','zoom',etc


Solution

  • Simpler way to do it without foreach(), assuming that there are no newlines in the input string:

    $str = 'position: 34.032616, -118.286564|heading: -159.50240187408838|pitch: 0|zoom: 2';
    $str = str_replace(array('|',':'), array('&','='), $mysql_data);
    
    parse_str($str, $pov);
    
    print_r($pov);
    /*
    Array
    (
        [position] =>  34.032616, -118.286564
        [heading] =>  -159.50240187408838
        [pitch] =>  0
        [zoom] =>  2
    )
    */
    

    If there are newlines in the input string, change the rules in the str_replace args.

    str_replace(array("\r\n","\n",'|',':'), array('','','&','='), $mysql_data);