php - 在 JSON 中使用 1 和 0 代替 True 和 False

标签 php json casting boolean type-conversion

在 PHP 中,我注意到如果我有一个数组,然后使用 json_encode() 它, boolean 值就会转换为 truefalse >。但是,我希望它们分别转换为 10

这是一个例子:

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

以上输出:

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

但是,如果 truefalse 分别为 10,我们可以得到更短的字符串,通过互联网传输所需的时间更少:

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

如何让 PHP 使用 10 而不是 truefalse 编码 JSON?

最佳答案

我明白了。在对 JSON 进行编码之前,您可以使用 PHP 中的 array_walkarray_walk_recursive 函数将 boolean 值转换为整数。我写了一个函数来做到这一点:

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}

关于php - 在 JSON 中使用 1 和 0 代替 True 和 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12022808/

相关文章:

c++ - 为什么 const_cast 的行为不如预期?

php - 更新mysql记录时获取纯数组文本

c# - 是否有一种 "cheap and easy"方法可以判断一个对象是否对特定类型实现了显式/隐式转换运算符?

php - 删除 WooCommerce 中最小购物车总数和特定国家/地区的所有税费

ios - 如何根据页码排列 JSON 解析数组?

javascript - AJAX 查询 |访问返回的对象数据

json - 如何在 JSONPath 中按字符串过滤?

c++ - C++程序在Visual Studio 2010中编译,但不能在Mingw中编译

php - Laravel DB::statement CREATE DATABASE 无法添加参数(准备语句?)

javascript - 由 JQuery load() 注入(inject) DIV 的 PHP 文件可以找到有关该 DIV 的任何信息吗?