使用PHP在JSON中附加新数据

时间:2018-10-18 18:04:00

标签: 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",
        "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)不存在的情况下添加数据,我的问题是: 例如如何在中间添加数据。我的代码只能编辑索引为nr的问题。 10.但不能添加索引为10的问题并推送所有下一个问题(索引为10的问题必须为11,依此类推)。我的json数据有70k行代码。 20个主要主题...

1 个答案:

答案 0 :(得分:1)

要在现有数组的特定位置插入新项目,可以将array_splice()与0一起使用作为第三个参数:

$existingArray = json_decode($jsonString, true);
$newItem = ['title' => 'Foo', 'id' => 'bar', ... ];
array_splice($existingArray[$title], $newPosition, 0, [$newItem]);

$existingArray现在将在位置$newItem处插入$newPosition

请注意,这不会不会更改您的id元素的值,如果需要,您必须自己执行操作。