JSON_NUMERIC_CHECK和电话号码 [英] JSON_NUMERIC_CHECK and phone numbers
问题描述
我们的PHP API使用启用了JSON_NUMERIC_CHECK的json_encode输出结果,这对于财务数据,二进制值等非常重要.但是我们最近引入了电话号码字段,该字段在转换时从数字开头删除零它是一个整数.
Our PHP API outputs results using json_encode with JSON_NUMERIC_CHECK enabled, which is important for financial figures, binary values etc.. but we have recently introduced a phone number field, and it is removing zeros from the beginning of the number when it casts it as an integer.
我尝试在值进入json_encode之前强制对其进行(字符串)"类型输入,但是该函数似乎覆盖了它.例如:
I've tried to force "(string)" type on the value before it goes to json_encode, but it looks like the function is overriding it. eg:
$output = array(
'is_bool' => 1,
'total_amount' => '431.65',
'phone_number' => (string) '0272561313'
);
echo json_encode($output,JSON_NUMERIC_CHECK);
产生:
{"is_bool":1,"total_amount":431.65,"phone_number":272561313}
任何有关如何最好地解决此问题的建议将不胜感激.我真的不想在输出电话号码时仅在电话号码的末尾添加尾随空格以使它作为字符串通过.
Any suggestions on how to best handle this would be much appreciated. I really don't want to have to resort to adding trailing spaces at the end of the phone number when it's output just to get it through as a string.
谢谢!
推荐答案
与其将类型转换为字符串,不如执行以下操作:
Instead of typecasting it to a string do something like this:
$output = array(
'is_bool' => 1,
'total_amount' => '431.65',
'phone_number' => '"0272561313"' // add quotations
);
echo '<pre>';
echo json_encode($output,JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
它将保持尾随零:
{
"is_bool": 1,
"total_amount": 431.65,
"phone_number": "\"0272561313\""
}
解码:
$test = json_encode($output,JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
$test = json_decode($test, true);
print_r($test);
输出:
Array
(
[is_bool] => 1
[total_amount] => 431.65
[phone_number] => "0272561313"
)
这篇关于JSON_NUMERIC_CHECK和电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!