Search code examples
phpassociative-arraytext-parsing

Parse a string with key=value declarations and make an associative array


How do I explode the following string:

$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368"

Such that the output array will contain:

[
    "ProductId" => "123",
    "Name" => "Ancient Roots, Modern Pursuits",
    "Country" => "India",
    "City" => "Bangalore",
    "Price" => "3368" 
]

I tried to explode by "comma", then each element again explode by "equal to" as.

$arr = explode(",", $str);

and again

$prodarr = explode("=", $arr[0]);  
$product["ProductId"] = $prodarr[1]

But I'm facing the problem when another comma exists in a value like in name Ancient Roots, Modern Pursuits.


Solution

  • Your structure is very weak for breaking. But you can still try to parse it.

    First explode on =. You will have next key and current value.

    Then loop these and explode on , and select last element for next key and all previous parts as value (sample):

    <?php
    $str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";
    
    $chunks = explode('=', $str);
    $keys = [];
    $values = [];
    
    foreach ($chunks as $i => $chunk) {
        $parts = explode(',', $chunk);
    
        if ($i != count($chunks) - 1) {
            $keys[] = trim(array_pop($parts));
        }
    
        if ($i != 0) {
            $values[] = implode(',', $parts);
        }
    }
    
    var_dump(array_combine($keys, $values));