[英]The JSON string doesn't get decoded
我有一个PHP
脚本,可通过哈希图从Android应用程序接收JSON字符串。
这是称为obj
的json字符串:
{
"total": "25",
"buyer_id": "1",
"order": [
{ "id": "1", "name": "cosmo" },
{ "id": "5", "name": "Choco" },
{ "id": "22", "name": "gogo" }
]
}
这是脚本
$json = $_POST['obj'];
$data = json_decode($json,true);
//initialize the variables to the json object param
$buyer_id = $data->buyer_id;
$total = $data->total;
//insert the order in the orders table
$sql_orders = "insert into orders(buyer_id,total) values
('$buyer_id','$total')";
$res = mysqli_query($con,$sql_orders);
在我看来,json_decode无法正常工作,因为变量为空; 当我echo
任何变量时:
echo $data.total;
输出为NULL。
这是因为您为json_decode()
第二个参数提供了true
; 它导致对象被转换为关联数组。 因此,取消引用运算符( ->
)将不适用于$data
。 您应该尝试在不指定第二个参数的情况下调用json_decode()
。
注意:如果在JSON中使用数字值,则最好按以下方式使用它们:
{
"total": 25,
"buyer_id": 1,
"order": [
{
"id": 1,
"name": "cosmo"
}, {
"id": 5,
"name": "Choco"
}, {
"id": 22,
"name": "gogo"
}
]
}
可读性更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.