简体   繁体   English

如何在PHP中将新记录添加到多维数组中?

[英]How to add a new record into a multidimensional array in PHP?

I would like to add a new entry to this into the "votes" section:我想在“投票”部分添加一个新条目:

["blue",[true, false]] 
{   "votes":[
     ["white",[true, true]],
     ["green",[true, false]]
   ],
   "config":{
      "title":"TEST",
      "options":[
         "first",
         "second"
      ]
   }
}

My code:我的代码:

$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);

The new record will only be appended to the JSon array.新记录只会附加到 JSon 数组。 How do I get a new entry under the section "votes"?如何在“投票”部分下获得新条目?

Your snippet doesn't work because you are trying to add new value into the root node.您的代码段不起作用,因为您正在尝试向根节点添加新值。 Also, you have a typo with your boolean values inside votes node此外,您在votes节点内的布尔值有错字

You should select the votes node like this:您应该像这样选择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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM