views:

55

answers:

7

How can i array a string, in the format that $_POST does... kind of, well i have this kind of format coming in:

101=1&2020=2&303=3

(Incase your wondering, its the result of jQuery Sortable Serialize... I want to run an SQL statement to update a field with the RIGHT side of the = sign, where its the left side of the equal sign? I know the SQL for this, but i wanted to put it in a format that i could use the foreach($VAR as $key=>$value) and build an sql statement from that.. as i dont know how many 101=1 there will be?

I just want to explode this in a way that $key = 101 and $value = 1

Sounds confusing ;) Thanks so so much in advanced!!

+1  A: 

One quick and dirty solution:

<?php
$str = "101=1&2020=2&303=3";
$VAR = array();
foreach(explode('&', $str) AS $pair)
{
    list($key, $value) = each(explode('=', $pair));
    $VAR[$key] = $value;
}
?>
JP
My answer, but with code to go with it. +1.
Thomas Owens
@JP: no need to reinvent the wheel. PHP has this functionality built-in: parse_str();
Asaph
Kudos! Just haven't coded in PHP for a while, forgot about this one; plus isn't the semantic behind the name parse_str() a bit wide? :)
JP
@JP: Does it really surprise you to see a badly named function in the PHP standard library? :)
Lukáš Lalinský
@Lukas: Oh wait, it's "standard"? :p
JP
+5  A: 

See the parse_str function.

Lukáš Lalinský
A: 

Explode on the & to get an array that contains [ 101=1 , 2020=2 , 303=3 ] then for each element, split on the = and push the key/value pair onto a new array.

Thomas Owens
+2  A: 

It's not the most intuitive function name in PHP but the function you're looking for is parse_str(). You can use it like this:

$myArray = array();
parse_str('101=1&2020=2&303=3', $myArray);
print_r($myArray);
Asaph
nice, I had no idea about this! very useful function, and one I'm sure has been rewritten thousands of times by people that didn't know about it.
GSto
A: 
$input = "101=1&2020=2&303=3";
$output = array();
$exp = explode('&',$input);
foreach($exp as $e){
   $pair = explode("=",$e);
   $output[$pair[0]] = $pair[1];
}
GSto
+1  A: 
parse_str($query_string, $array_to_hold_values);
Anti Veeranna
+1  A: 

Why bother with parse_str() or exploding a string? For example, what if you run into "=" that is actually the part of data you need? You already get the parameters from query string as an associative array in superglobal $_GET array:

foreach ($_GET as $key => $value) {
    /**
     * Optional validation of $value or some checks here
     */

    // your array with safe and valid data, ready for inserting
    $yourArray[$key] = $value; // consider mysql_real_escape()
}
Oliver