【发布时间】:2014-03-06 23:19:38
【问题描述】:
我有一个 JSON 文件,其中包含以下内容:
{"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"}]}
【问题讨论】:
-
尝试使用“by reference”,如
foreach($obj->faqitem as $key => &$val ) { -
这没什么区别,我仍然在文件中得到重复的值。
{"faqitem":[{"id":"faq1","question":"Question 1"},{"id":"faq2","question":"This is the updated question"},{"id":"faq2","question":"This is the updated question"}]} -
公平地说,通过eval.in/114925 运行它似乎工作正常......在您的示例中,您的数据 is 不同,因此它应该添加一个新密钥。如果将
$newdata数组中的faq2更改为faq1,它确实会被覆盖。 -
它可以很好地写入文件,但是,假设我有一个 ID 为“faq2”的对象。它没有更新该对象,而是附加了一个 ID 为“faq2”的新对象。我不希望它那样工作。如果 id 存在则需要更新。
-
是的,很酷,您能否在您的问题中包含一个示例,因为您提供的内容很好。