views:

148

answers:

3

I have a reasonably large number of variables encoded in the form:

 foo=bar&spam[eggs]=delicious&...

These are all in a single string (eg, $data = "foo=bar&spam[eggs]=delicious&..."). The variables are arbitrarily deeply nested -- easily four or five levels deep ("spam[eggs][bloody][vikings]=loud").

Is there an easy, reliable way to get a multi-dimensional PHP array from this? I assume PHP has a parser to do this, though I don't know if it's exposed for my use. Ideally, I could do something like:

// given $data == "foo=bar&spam[eggs]=delicious"
$arr = some_magical_function( $data );
/* arr = Array
    (
        [foo] => bar
        [spam] => Array
            (
                [eggs] => delicious
            )
    )
*/
+5  A: 

If your string is in URI params format, parse_str is the magic function you are looking for.

deceze
+2  A: 

You might want to take a look at parse_str ; here's an example :

$str = "first=value&arr[]=foo+bar&arr[]=baz";

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

And, with your input :

$str = 'oo=bar&spam[eggs]=delicious&spam[eggs][bloody][vikings]=loud';
$output = array();
parse_str($str, $output);
var_dump($output);

You'll get this :

array
  'oo' => string 'bar' (length=3)
  'spam' => 
    array
      'eggs' => 
        array
          'bloody' => 
            array
              'vikings' => string 'loud' (length=4)

Which should be what you want ;-)

(notice the multi-level array ; and the fact that ths first spam[eggs] has been overriden by the second one, btw)

Pascal MARTIN
+1  A: 

If your data comes from the request uri, use $_GET

troelskn