Update JSON value if exists otherwise add it in PHP

后端 未结 2 1222
太阳男子
太阳男子 2021-01-28 04:13

I have a JSON file that contains the following:

{\"faqitem\": [{ \"id\": \"faq1\", \"question\": \"Question 1\"}]}

I am trying to do two things

2条回答
  •  别那么骄傲
    2021-01-28 05:02

    So take the whole JSON aspect out of it. That is just serialization. Think about how to make the data structure look the way you want. Think about your data structure. To me, it seems that is maybe not the best structure for your purposes and that perhaps you need your id available as a lookup key, so when you add an item to the data structure your either create a new value at that id key or overwrite the value at that key.

    If your data were structured like:

    {"faqitem":
        {
            "faq1": "Faq content",
            "faq2": "Faq 2 content"
        }
    }
    

    Then your code code be as simple as:

    $faqpage = 'includes/faq.json';

    $file = file_get_contents($faqpage);    
    $obj = json_decode($file); 
    
    $newdata['id'] = "faq2";
    $newdata['question'] = "This is the second question";
    
    $obj->faqitem->{$newdata['id']} = $newdata['question'];
    
    echo json_encode($obj);
    
    $fh = fopen($faqpage, 'w') or die ("can't open file");  
    //okay now let's open our file to prepare it to write
    fwrite($fh, json_encode($obj));
    fclose($fh);
    

提交回复
热议问题