duanpuluan0480 2014-03-06 23:19
浏览 31
已采纳

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

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"}]}
  • 写回答

2条回答 默认 最新

  • duanqie5741 2014-03-06 23:43
    关注

    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);
    }
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64