PHP函数从数组构建查询字符串 - 而不是http构建查询
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 ones and zeros for me. I am building a little PHP wrapper for the Stack Overflow api and parsing an option array and then sending this onto the api breaks things..(doesn't like 1 for true).
What I would like is a simple function to turn a single dimensional array into a query string but turning true/false into string values of true/false.
Anyone know of anything that can do this before I start re-inventing the wheel
您好我知道所有关于 http://www.php.net/manual/en/function.http-build-query.php 这样做但是我有 一个小问题。 p>
它“handly”将布尔值转换为1和0。 我正在为Stack Overflow api构建一个小的PHP包装器并解析一个选项数组,然后将它发送到api中断的东西..(不喜欢1表示true)。 p>
什么 我想要一个简单的函数将一个单维数组转换为查询字符串,但将true / false转换为字符串值true / false。 p>
任何人都知道任何事情可以做到这一点之前 我开始重新发明轮子 p> div>
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);
Try passing http_build_query true and false as strings instead of booleans. You may get different results.
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()
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
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);
}