I have a JSON file that contains the following:
{\"faqitem\": [{ \"id\": \"faq1\", \"question\": \"Question 1\"}]}
I am trying to do two things
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);
}
...