PHP function to build query string from array - not http build query

前端 未结 5 1997
终归单人心
终归单人心 2021-01-19 10:49

Hello I know all about http://www.php.net/manual/en/function.http-build-query.php to do this however I have a little problem.

It \"handly\" turns boolean values into

相关标签:
5条回答
  • 2021-01-19 11:28

    I don't know of anything offhand. What I'd recommend is first iterating through the array and covert booleans to strings, then call http_build_query

    E.g.

    foreach($options_array as $key=>$value) :
        if(is_bool($value) ){
            $options_array[$key] = ($value) ? 'true' : 'false';
        }
    endforeach;
    $options_string=http_build_query($options_array);
    
    0 讨论(0)
  • 2021-01-19 11:30

    Try passing http_build_query true and false as strings instead of booleans. You may get different results.

    0 讨论(0)
  • 2021-01-19 11:33

    If you just need to convert your true/false to "true"/"false":

    function aw_tostring (&$value,&$key) {
      if ($value === true) {
        $value = 'true';
      }
      else if ($value === false) {
        $value = 'false';
      }
    }
    
    array_walk($http_query,'aw_tostring');
    
    // ... follow with your http_build_query() call
    
    0 讨论(0)
  • 2021-01-19 11:41

    have a look at my wheel:

    function buildSoQuery(array $array) {
        $parts = array();
        foreach ($array as $key => $value) {
            $parts[] = urlencode($key).'='.(is_bool($value)?($value?'true':'false'):urlencode($value));
        }
        return implode('&', $parts);
    }
    
    0 讨论(0)
  • 2021-01-19 11:44

    Loop through each variable of the query string ($qs) and if bool true or false, then change value to string.

    foreach($qs as $key=>$q) {
        if($q === true) $qs[$key] = 'true';
        elseif($q === false) $qs[$key] = 'false';
    }
    

    Then you can use the http_build_query()

    0 讨论(0)
提交回复
热议问题