http_build_query 参数没有值(空值)
http_build_query without value on parameters (null value)
PHP 函数 http_build_query 对于构建带有 GET 参数的 URL 非常方便。但有时我喜欢使用无值的 "boolean" 参数,例如:
/mypage?subscription-id=42&cancel-renewal
然后我用一个简单的 isset
进行检查。我可以用 http_build_query
实现这个结果吗?
编辑: 为参数分配空值似乎不起作用:
cancel-renewal => ''
结果为 cancel-renewal=
cancel-renewal => null
导致参数被省略
cancel-renewal => false
结果为 cancel-renewal=0
使用这个;
$query = array("subscription-id" => 42, "cancel-renewal" => "");
$http_query = http_build_query($query);
这将 return ?subscription-id=42&cancel-renewal=
。并且与 isset()
完美配合
Can I achieve this result with http_build_query?
没有。在内部 http_build_query
附加 =
键值分隔符,无论参数的值是什么。
可以看源码 here (PHP 7.3.3)
意味着您要么需要接受参数的 cancel-renewal=
外观,要么可以重新设计路径以具有类似 /mypage/cancel-renewal?subscription-id=42
的内容
第三个选项是编写您自己的简单函数来构建查询字符串。
PHP 函数 http_build_query 对于构建带有 GET 参数的 URL 非常方便。但有时我喜欢使用无值的 "boolean" 参数,例如:
/mypage?subscription-id=42&cancel-renewal
然后我用一个简单的 isset
进行检查。我可以用 http_build_query
实现这个结果吗?
编辑: 为参数分配空值似乎不起作用:
cancel-renewal => ''
结果为cancel-renewal=
cancel-renewal => null
导致参数被省略cancel-renewal => false
结果为cancel-renewal=0
使用这个;
$query = array("subscription-id" => 42, "cancel-renewal" => "");
$http_query = http_build_query($query);
这将 return ?subscription-id=42&cancel-renewal=
。并且与 isset()
Can I achieve this result with http_build_query?
没有。在内部 http_build_query
附加 =
键值分隔符,无论参数的值是什么。
可以看源码 here (PHP 7.3.3)
意味着您要么需要接受参数的 cancel-renewal=
外观,要么可以重新设计路径以具有类似 /mypage/cancel-renewal?subscription-id=42
第三个选项是编写您自己的简单函数来构建查询字符串。