在 PHP 中,我注意到如果我有一个数组,然后使用 json_encode()
它, boolean 值就会转换为 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
,我们可以得到更短的字符串,通过互联网传输所需的时间更少:
{"foo":1,"bar":0,"baz":0,"biz":1}
如何让 PHP 使用 1
和 0
而不是 true
和 false
编码 JSON?
最佳答案
我明白了。在对 JSON 进行编码之前,您可以使用 PHP 中的 array_walk
或 array_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/