在 PHP http_build_query 中将布尔值转换为真正的 true 和 false 字符串

Convert booleans to real true and false strings in PHP http_build_query

如前所述 here PHP 的 http_build_query 函数将结果字符串中的布尔值转换为整数。

有没有办法:

$a = ["teste1" => true, "teste2" => false];
echo http_build_query($a);

结果可以是teste1=true&teste2=false

主要问题是因为我有一个 JSON 应该转换为查询字符串并对参数进行排序。我的逻辑是:

$json = file_get_contents('php://input');
$decoded = json_decode($json, true);
$query = http_build_query($decoded);
$exploded = explode('&', $query);
sort($exploded);
$params = implode('&', $exploded);

但结果字符串包含 01 而不是 falsetrue。你有什么建议吗?

将 JSON 解码为数组后,

$json = file_get_contents('php://input');    
$decoded = json_decode($json, true);

您可以使用ksort按键排序。然后你只需要使用 http_build_query 一次而不是 implode/explode,等等

ksort($decoded);

$params = http_build_query(array_map('boolsToString', $decoded));

function boolsToString ($value) {
    if ($value === true) return 'true';    // strict comparison with === is necessary
    if ($value === false) return 'false';
    return $value;
}

我想出了解决我的问题的方法,我忘了提到 JSON 被解码为多维数组,所以:

function normalizeArray($array) {
  foreach ($array as &$el) {
      if (is_bool($el)) {
        $el = ($el) ? "true" : "false";
      } elseif (is_array($el)) {
        $el = normalizeArray($el);
      }
  }
  return $array;
}


$json = file_get_contents('php://input');
$decoded = json_decode($json, true);
$normalized = normalizeArray($decoded);

$query = http_build_query($normalized);
$exploded = explode('&', $query);
sort($exploded);
$params = implode('&', $exploded);

我仍然坚持使用 explode/implode 解决方案,那是因为 http_build_query 使多维键正确地像: level1[level2][level3]=something 并且使用以前的解决方案我失去了 "parent" 级别键名。