php url query nested array with no index

I very much agree with the answer by RiaD, but you might run into some problems with this code (sorry I can't just make this a comment due to lack of rep).

First off, as far as I know http_build_query returns an urlencode()'d string, which means you won't have [ and ] but instead you'll have %5B and %5D.

Second, PHP's PCRE engine recognizes the '[' character as the beginning of a character class and not just as a simple '[' (PCRE Meta Characters). This may end up replacing ALL digits from your request with '[]'.

You'll more likely want something like this:

preg_replace('/\%5B\d+\%5D/', '%5B%5D', http_build_query($params));

In this case, you'll need to escape the % characters because those also have a special meaning. Provided you have a string with the actual brackets instead of the escapes, try this:

preg_replace('/\[\d+\]/', '[]', $http_query);

There doesn't seem to be a way to do this with http_build_query. Sorry. On the docs page though, someone has this:

function cr_post($a,$b=0,$c=0){
    if (!is_array($a)) return false;
    foreach ((array)$a as $k=>$v){
        if ($c) $k=$b."[]"; elseif (is_int($k)) $k=$b.$k;
        if (is_array($v)||is_object($v)) {
            $r[]=cr_post($v,$k,1);continue;
        }
        $r[]=urlencode($k)."=" .urlencode($v);    
    }
    return implode("&",$r);
}


$params['text'][] = 'Hello World';
$params['text'][] = 'How are you?';
$params['html'][] = '<p>Just fine, thank you</p>';

$str = cr_post($params);
echo $str;

I haven't tested it. If it doesn't work then you're going to have to roll your own. Maybe you can publish a github gist so other people can use it!


I don't know a standard way to do it (I think there is no such way), but here's an ugly solution:

Since [] is encoded by http_build_query, you may generate string with indices and then replace them.

preg_replace('/(%5B)\d+(%5D=)/i', '$1$2', http_build_query($params));