php url query nested array with no index

前端 未结 4 1143
清歌不尽
清歌不尽 2021-01-11 15:28

I\'m working with a third party API that receives several parameters which must be encoded like this:

text[]=Hello%20World&text[]=How%20are%20you?&ht         


        
相关标签:
4条回答
  • 2021-01-11 16:16

    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));
    
    0 讨论(0)
  • 2021-01-11 16:27

    Try this:

    $params['text'][] = 'Hello World';
    $params['text'][] = 'How are you?';
    $params['html'][] = '<p>Just fine, thank you</p>';
    foreach ($params as $key => $value) {
        foreach ($value as $key2 => $value2) {        
            $http_query.= $key . "[]=" . $value2 . "&";
        }
    }
    $http_query = substr($http_query, 0, strlen($http_query)-1); // remove the last '&'
    $http_query = str_replace(" ", "%20", $http_query); // manually encode spaces
    echo $http_query;
    
    0 讨论(0)
  • 2021-01-11 16:28

    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!

    0 讨论(0)
  • 2021-01-11 16:32

    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);
    
    0 讨论(0)
提交回复
热议问题