Piotr Mirosz
Piotr Mirosz

Reputation: 866

append new data in JSON using PHP

i have specific question...

my JSON structue

{"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}]

That's how i open json file:

$jsonString = file_get_contents('../question.json');
$data = json_decode($jsonString, true);

That's the way to add/edit some data:

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

but, i can add data only if index ($idnum) not exist, my question is: How do add data for example in middle. My code can only edit for example question with index nr. 10. but can't add question with index 10 and push all next questions(question with index 10 need to be 11 and etc.). my json data have 70k lines of code. 20 main topics...

Upvotes: 0

Views: 63

Answers (1)

Alex Howansky
Alex Howansky

Reputation: 53646

To insert a new item at a certain location in an existing array, you can use array_splice() with 0 for the third argument:

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

$existingArray will now contain $newItem inserted at position $newPosition.

Note that this will not change the value of your id elements, you'll have to do that yourself if desired.

Upvotes: 1

Related Questions