Update JSON value if exists otherwise add it in PHP

后端 未结 2 1223
太阳男子
太阳男子 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 04:52

    Your problem is that your logic is incorrect. In the first iteration the ID doesn't match so $newdata will be added. In the second iteration the ID match and the item is going to be updated - but wait. We just added this item in previous iteration! So your loop part should looks like this:

    ...
    $exists = false;
    foreach($obj->faqitem as $key => $val)
    {
        // update if exists
        if($val->id == $newdata['id']) {
            $val->question = $newdata['question'];
            $exists = true;
        }
    }
    
    // add new if not exists
    if(!$exists) {
        $newstuff = new stdClass;
        $newstuff->id = $newdata['id'];
        $newstuff->question = $newdata['question'];     
        array_push($obj->faqitem, $newstuff);
    }
    ...
    

提交回复
热议问题