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

share|improve this question
I've updated my answer to include a regular expression that solves the same problem with less hacks than parse_str() :) – Jack Jun 4 '12 at 6:11

2 Answers

up vote 1 down vote accepted

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);
share|improve this answer
is there any difference between $mysql_data = trim($mysql_data); and adding \n to the str_replace() function? – Omar Jun 4 '12 at 3:58
trim() will remove the whitespaces from both ends of $mysql_data. While the code above doesn't really care with whitespaces. It just converts the string to array the way you want. – bsdnoobz Jun 4 '12 at 4:02
I had no idea you could use str_replace in combination with arrays :O I learned a new thing today. BTW, Thank you! Your answer covers both of my questions and a bit more =) – Omar Jun 4 '12 at 4:16

There's a newline in front of heading.

Inside your loop you should trim() the array key (and value just in case):

$pov[ trim($element[0]) ] = trim($element[1]);

Update

A simple regular expression will also take care of this:

$s = <<<EOM
position: 34.032616, -118.286564|
heading: -159.50240187408838|
pitch: 0|
zoom: 2
EOM;

if (preg_match_all('/(\w+):([^|]+)/', $s, $matches)) {
    $pov = array_combine($matches[1], $matches[2]);
}

Btw: don't use parse_str hacks, that function is meant for data that's already properly URL encoded and quite honestly is the wrong tool for the job.

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.