[英]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.