我想到了。在对 JSON 进行编码之前,您可以使用 PHP 中的array_walk
orarray_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}