存在,否則它添加我有一個包含以下內容的JSON文件:更新JSON值,如果在PHP
{"faqitem": [{ "id": "faq1", "question": "Question 1"}]}
我試圖做兩件事情。如果它存在,則更新一個特定值;如果不存在,則更新一個新值。
目前,我能夠更新文件,但它只是不斷增加新的值,如果它已經存在,永遠不會更新。
$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/>\n";
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);
這裏是重複的對象ID輸出例如:
{"faqitem":[{"id":"faq1","question":"Question 1"},{"id":"faq2","question":"This is the updated question"},{"id":"faq2","question":"This is the updated question"}]}
嘗試使用 「按引用」 像'的foreach($ obj-> faqitem爲$鍵=>&$ VAL){' – djot
這沒有什麼區別,我仍然在文件中得到重複值。 '{「faqitem」:[{「id」:「faq1」,「question」:「Question 1」},{「id」:「faq2」,「question」:「This is the updated question」 {「id」:「faq2」,「question」:「這是更新後的問題」}]} – plumwd
@djot:爲了什麼? ... – zerkms