I have a JSON file that contains the following:
{"faqitem": [{ "id": "faq1", "question": "Question 1"}]}
I am trying to do two things. Update a particular value if it exists OR add a new value if it doesn't.
Currently, I am able to update the file, but it just keeps adding new values and never updates if it already exists.
$faqpage = 'includes/faq.json';
$file = file_get_contents($faqpage);
$obj = json_decode($file);
$newdata['id'] = "faq2";
$newdata['question'] = "This is the second question";
foreach($obj->faqitem as $key => $val ) {
echo "IDS " . $val->id . " = " . $newdata['id'] . "<br/>
";
if ($val->id == $newdata['id']) {
$val->question = $newdata['question'];
echo $val->id . "<br/>match<br/>";
} else {
$newstuff = new stdClass;
$newstuff->id = $newdata['id'];
$newstuff->question = $newdata['question'];
array_push($obj->faqitem, $newstuff);
echo "<br/>no match<br/>";
}
}
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);
Here is an example output with duplicated object ids:
{"faqitem":[{"id":"faq1","question":"Question 1"},{"id":"faq2","question":"This is the updated question"},{"id":"faq2","question":"This is the updated question"}]}