Search code examples
phparraysquery-stringsubmissionurl-parsing

Parse querystring with delimited keys into a 2d associative array


I'm trying to convert a serialized string into an array

This is the string I'm getting on php (form sent using serialized AJAX POST):

ref_1=000CBA0000&name_1=Produto%20A&quantity_1=1&ref_2=000CBA0000&name_2=Produto%20A&quantity_2=1&ref_3=000CBA0000&name_3=Produto%20A&quantity_3=1

Every product that comes in the string have its own ref,name,quantity, so currently my string comes with the information of 3 products, it may change every request.

I'm trying to convert the serialized string to an array with this format

[
    [1]
        ref => <copy the value from ref_1>
        name => <copy the value from name_1>
        quantity => <copy the value from quantity_1>
    [2]
        ref => <copy the value from ref_2>
        name => <copy the value from name_2>
        quantity => <copy the value from quantity_2>

    [3] 
        ref => <copy the value from ref_3>
        name => <copy the value from name_3>
        quantity => <copy the value from quantity_3>
]

So later I can do a foreach product and fetch them individually.

I tried exploding the string with:

$array = explode("&",$string);
var_dump($array);

but that gives me a different result:

array(9) {
    [0]=> string(16) "ref_1=000CBA0000"
    [1]=> string(21) "name_1=Produto%20A"
    [2]=> string(12) "quantity_1=1"
    [3]=> string(16) "ref_2=000CBA0000"
    [4]=> string(21) "name_2=Produto%20A"
    [5]=> string(12) "quantity_2=1"
    [6]=> string(16) "ref_3=000CBA0000"
    [7]=> string(21) "name_3=Produto%20A"
    [8]=> string(12) "quantity_3=1"
}

Solution

  • You can use parse_str() to parse the parameters then loop over the array and explode() the key to get the key name and key number separately.

    parse_str("ref_1=000CBA0000&name_1=Produto%20A&quantity_1=1&ref_2=000CBA0000&name_2=Produto%20A&quantity_2=1&ref_3=000CBA0000&name_3=Produto%20A&quantity_3=1", $arr);
    
    
    foreach($arr as $key => $val){
        $temp = explode("_", $key);
        $new[$temp[1]][$temp[0]] = $val;
    }
    var_dump($new);
    

    Gives:

    array(3) {
      [1]=>
      array(3) {
        ["ref"]=>
        string(10) "000CBA0000"
        ["name"]=>
        string(9) "Produto A"
        ["quantity"]=>
        string(1) "1"
      }
      [2]=>
      array(3) {
        ["ref"]=>
        string(10) "000CBA0000"
        ["name"]=>
        string(9) "Produto A"
        ["quantity"]=>
        string(1) "1"
      }
      [3]=>
      array(3) {
        ["ref"]=>
        string(10) "000CBA0000"
        ["name"]=>
        string(9) "Produto A"
        ["quantity"]=>
        string(1) "1"
      }
    }
    

    https://3v4l.org/WVGiv

    As Cid mentions, this will work as long as the keys have an underscore in the name separating the name and the number, in that order.
    If it doesn't it will fail.