PHP, Convert a string with brackets into an array

php, regex

Solution

References are your friend here:

$result = array();

foreach ($inputArray as $key => $val) {
    $keyParts = preg_split('/[\[\]]+/', $key, -1, PREG_SPLIT_NO_EMPTY);

    $ref = &$result;

    while ($keyParts) {
        $part = array_shift($keyParts);

        if (!isset($ref[$part])) {
            $ref[$part] = array();
        }

        $ref = &$ref[$part];
    }

    $ref = $val;
}

Demo

However, there is another, much simpler way, although it is a little less efficient in terms of functional complexity:

parse_str(http_build_query($inputArray), $result);

Demo

Problem

I am querying an API and it sends a JSON response which I am then decoding into an array. This part works fine, but the API sends the information in a rather unfriendly format. I will paste the part I am having issues with. Essentially I am trying to change each like keys into their own array. ``` Array ( [name] => Name [address] => 123 Street Rd [products[0][product_id]] => 1 [products[0][price]] => 12.00 [products[0][name]] => Product Name [products[0][product_qty]] => 1 [products[1][product_id]] => 2 [products[1][price]] => 3.00 [products[1][name]] => Product Name [products[1][product_qty]] => 1 [systemNotes[0]] => Note 1 [systemNotes[1]] => Note 2 ) ``` Now what I would like to do is to make it like this: ``` Array ( [name] => Name [address] => 123 Street Rd [product] => Array ( [0] => Array ( [product_id] => 1 [price] => 12.00 [name] => Product Name [product_qty] => 1 ) [1] => Array ( [product_id] => 2 [price] => 3.00 [name] => Product Name [product_qty] => 1 ) [systemNotes] => Array ( [0] => Note 1 [1] => Note 2 ) ) ``` Is there any practical way of doing this? Thanks!

Original source