更新JSON值(如果存在),否则将其添加到PHP中 [英] Update JSON value if exists otherwise add it in PHP
问题描述
我有一个包含以下内容的JSON文件:
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/>\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的示例输出:
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"}]}
推荐答案
您的问题是您的逻辑不正确.在第一次迭代中,ID不匹配,因此将添加$newdata
.在第二次迭代中,ID匹配和项目将被更新-但请稍候.我们只是在先前的迭代中添加了该项目!因此,您的循环部分应如下所示:
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);
}
...
这篇关于更新JSON值(如果存在),否则将其添加到PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!