PHP function to build a query string from an array - not an HTTP request

Hello, I know everything about http://www.php.net/manual/en/function.http-build-query.php , but I have a little problem.

It "manually" turns logical values ​​into units and zeros for me. I create a small PHP wrapper for Apache Overflow api and parse an array of parameters and then send it to api, breaks things .. (don't like 1 for true).

I would like a simple function to turn a one-dimensional array into a query string, but return true / false to string values ​​true / false.

Does anyone know anything that can do this before I start reinventing the wheel.

+3
source share
5 answers

. , http_build_query

.

foreach($options_array as $key=>$value) :
    if(is_bool($value) ){
        $options_array[$key] = ($value) ? 'true' : 'false';
    }
endforeach;
$options_string=http_build_query($options_array);
+4

http_build_query true false booleans. .

+1

If you just need to convert true/ falseto "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
+1
source

Scroll each query string variable ($ qs), and if bool is true or false, change the value to a string.

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

Then you can use http_build_query()

0
source

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
source

Source: https://habr.com/ru/post/1753194/


All Articles