使用PHP在JSON中追加新数据
我有一个具体的问题 我的JSON结构使用PHP在JSON中追加新数据,php,json,Php,Json,我有一个具体的问题 我的JSON结构 {"Math":[ { "title":"Math", "subtitle": "some txt", "subtitle2" : "some txt", "id": "1", "date":"08J", "question":"some txt", "ans01": "some txt1", "ans02": "some txt2"
{"Math":[
{ "title":"Math",
"subtitle": "some txt",
"subtitle2" : "some txt",
"id": "1",
"date":"08J",
"question":"some txt",
"ans01": "some txt1",
"ans02": "some txt2",
"ans03": "some txt3",
"ans04": "some txt4",
"ans05": "some txt5",
"correct": "some txt2",
"ans01count": 0,
"ans02count": 0,
"ans03count": 0,
"ans04count": 0,
"ans05count": 0
},
{ same as above couple times}],
"Psychic":[
{ "title":"Math",
"subtitle": "some txt",
"subtitle2" : "some txt",
"id": "1",
"date":"08J",
"question":"some txt",
"ans01": "some txt1",
"ans02": "some txt2",
"ans03": "some txt3",
"ans04": "some txt4",
"ans05": "some txt5",
"correct": "some txt2",
"ans01count": 0,
"ans02count": 0,
"ans03count": 0,
"ans04count": 0,
"ans05count": 0
},
{ same as above couple times}]
这就是我打开json文件的方式:
$jsonString = file_get_contents('../question.json');
$data = json_decode($jsonString, true);
这是添加/编辑某些数据的方法:
// $tit = title as on example 'Math'
$data[$tit][$idnum]['question'] = $quest;
$data[$tit][$idnum]['ans01'] = $ans1;
$data[$tit][$idnum]['ans02'] = $ans2;
$data[$tit][$idnum]['ans03'] = $ans3;
$data[$tit][$idnum]['ans04'] = $ans4;
$data[$tit][$idnum]['ans05'] = $ans5;
$data[$tit][$idnum]['correct'] = $corr;
$newJsonString = json_encode($data);
file_put_contents('../question.json', $newJsonString);
但是,我只能在索引$idnum不存在时添加数据,我的问题是:
例如,如何在中间添加数据。我的代码只能编辑索引为10的示例问题。但不能添加索引为10的问题并推送所有下一个问题索引为10的问题必须为11,等等。。我的json数据有70k行代码。20个主要议题 若要在现有数组中的某个位置插入新项,可以将array_splice与0一起用作第三个参数:
$existingArray = json_decode($jsonString, true);
$newItem = ['title' => 'Foo', 'id' => 'bar', ... ];
array_splice($existingArray[$title], $newPosition, 0, [$newItem]);
$existingArray现在将包含在$newPosition位置插入的$newItem
请注意,这不会更改id元素的值,如果需要,您必须自己进行更改。我的json数据有70k行代码,我认为是时候开始查看数据库了……我们很快会选择数据库,但不是现在。我们将重建整个项目,但现在我们需要它尽快工作;和数组_unshift;这只允许在开始时添加数据…可能使用array_slice将数组拆分为两个块,将新项添加到第一个块的末尾,然后使用array_merge将它们重新组合在一起。啊,是的,这里是array_splice:如果指定了长度且长度为零,则不会删除任何元素