【问题标题】:Use 1 and 0 Instead of True and False in JSON在 JSON 中使用 1 和 0 代替 True 和 False
【发布时间】:2012-08-14 21:45:29
【问题描述】:

在 PHP 中,我注意到如果我有一个数组,然后是 json_encode() 它,布尔值将转换为 true 和 false。但是,我希望它们分别转换为1 和0。

这是一个例子:

$data = Array("foo" => true, "bar" => false, "baz" => false, "biz" => true);
print json_encode($data);

以上输出:

{"foo":true,"bar":false,"baz":false,"biz":true}

但是,如果 true 和 false 分别是 1 和 0,我们可以有一个更短的字符串,这将花费更少的时间通过 Internet 传输:

{"foo":1,"bar":0,"baz":0,"biz":1}

如何使用1 和0 而不是true 和false 使PHP 编码JSON?

【问题讨论】:

    标签: php json casting boolean type-conversion


    【解决方案1】:

    我想通了。在编码 JSON 之前,您可以使用 PHP 中的 array_walk 或 array_walk_recursive 函数将布尔值转换为整数。我写了一个函数来做到这一点:

    function change_booleans_to_numbers(Array $data){
        // Note the order of arguments and the & in front of $value 
        function converter(&$value, $key){
            if(is_bool($value)){
                $value = ($value ? 1 : 0);
            }
        }
        array_walk_recursive($data, 'converter');
        return $data;
    }
    

    这是一个演示脚本:

    <?php
    // Make the browser display this as plain text instead of HTML 
    header("Content-Type:text/plain");
    
    function change_booleans_to_numbers(Array $data){
        function converter(&$value, $key){
            if(is_bool($value)){
                $value = ($value ? 1 : 0);
            }
        }
        array_walk_recursive($data, 'converter');
        return $data;
    }
    
    $data = Array("foo" => true, "bar" => false, "baz" => false, "biz" => true);
    
    print "Original:" . PHP_EOL;
    var_dump($data);
    print json_encode($data) . PHP_EOL;
    print PHP_EOL;
    
    $changed = change_booleans_to_numbers($data);
    print "Processed:" . PHP_EOL;
    var_dump($changed);
    print json_encode($changed) . PHP_EOL;
    

    脚本输出:

    Original:
    array(4) {
      ["foo"]=>
      bool(true)
      ["bar"]=>
      bool(false)
      ["baz"]=>
      bool(false)
      ["biz"]=>
      bool(true)
    }
    {"foo":true,"bar":false,"baz":false,"biz":true}
    
    Processed:
    array(4) {
      ["foo"]=>
      int(1)
      ["bar"]=>
      int(0)
      ["baz"]=>
      int(0)
      ["biz"]=>
      int(1)
    }
    {"foo":1,"bar":0,"baz":0,"biz":1}
    

    【讨论】:

    • 我强烈建议您在 JSON 消息中尽可能使用“true”和“false”(NOT“1”或“0”)。否则只是糟糕的形式。恕我直言...
    • 我更关心下载 JSON 需要多长时间。
    • 如果您认真尝试使用 1/0 而不是 true/false 来节省 3 个字节,那么您过早优化的可能性为 99.9999%。如果你不是,你正在从事可疑的微优化。还有很多更重要的事情,比如数据库和文件系统访问,它们对性能的影响更大。你应该听@paulsm4。
    • 我真的很难弄清楚为什么您认为 1992 年后的 Web 服务器提供的 GZIP 压缩无法处理“true”而不是 1 添加的额外几个字节。您通过将 bool 表示为 int 来歪曲值的类型。
    • 哦,是的,我忘了我的网络服务器启用了 GZIP。
    猜你喜欢
    • 2017-02-21
    • 2012-08-27
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多