[英]How to add a new record into a multidimensional array in PHP?
我想在“投票”部分添加一個新條目:
["blue",[true, false]]
{ "votes":[
["white",[true, true]],
["green",[true, false]]
],
"config":{
"title":"TEST",
"options":[
"first",
"second"
]
}
}
我的代碼:
$jsonString = file_get_contents('./data/'.$_GET['id']);
$data = json_decode($jsonString, true);
// insert a new record
$data[] = array("votes" => "blue",true, true);
$newJsonString = json_encode($data);
file_put_contents('./data/'.$_GET['id'], $newJsonString);
新記錄只會附加到 JSon 數組。 如何在“投票”部分下獲得新條目?
您的代碼段不起作用,因為您正在嘗試向根節點添加新值。 此外,您在votes
節點內的布爾值有錯字
您應該像這樣選擇votes
節點:
$jsonString = file_get_contents('./data/'.$_GET['id']);
$data = json_decode($jsonString, true);
// insert a new record into votes node
$data['votes'][] = ["blue", [true, true]];
$newJsonString = json_encode($data);
file_put_contents('./data/'.$_GET['id'], $newJsonString);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.