如果存在则更新JSON值,否则将其添加到PHP中

时间:2014-03-06 23:19:38

标签: php json

我有一个包含以下内容的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"}]}

2 个答案:

答案 0 :(得分:1)

您的问题是您的逻辑不正确。在第一次迭代中,ID不匹配,因此将添加$newdata。在第二次迭代中,ID匹配和项目将更新 - 但等待。我们刚刚在上一次迭代中添加了这个项目!所以你的循环部分应该是这样的:

...
$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);
}
...

答案 1 :(得分:0)

所以从中获取整个JSON方面。那只是序列化。考虑如何使数据结构看起来像您想要的那样。考虑一下您的数据结构。对我而言,似乎可能不是最适合您目的的结构,也许您需要将id作为查找键,因此当您向数据结构中添加项目时,您可以在此处创建新值id键或覆盖该键的值。

如果您的数据结构如下:

{"faqitem":
    {
        "faq1": "Faq content",
        "faq2": "Faq 2 content"
    }
}

然后你的代码就像:

一样简单

$ faqpage ='includes / faq.json';

$file = file_get_contents($faqpage);    
$obj = json_decode($file); 

$newdata['id'] = "faq2";
$newdata['question'] = "This is the second question";

$obj->faqitem->{$newdata['id']} = $newdata['question'];

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);