首页 > 解决方案 > php根据条件更新json数据

问题描述

我有一个带有以下 json 数据的文本文件-

{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Sorry, this message is not understandable to me."}}}
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"But I will learn this in next few days."}}}
{"sender":"175","time":15,"message":"update next","response":{"recipient":{"id":"17"},"message":{"text":"this will be updated next."}}}
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Anything else you want to ask me?"}}}

我想根据两个标准更新第三条记录:

  1. “身份证”:“17”
  2. “消息”:“下一个更新”

我想要的第三条记录的输出 -

{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Meanwhile, please wait for our representative to get back to you."}}}

请帮我用php更新记录。

标签: phpjson

解决方案


首先,您需要创建一个有效的 JSON,然后您必须将 JSON 转换为数组,然后您必须遍历数组并找到与条件匹配的项目,最后更改值。

JSON 文件内容(文件名:items.json):

 [
   {"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Sorry, this message is not understandable to me."}}},
   {"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"But I will learn this in next few days."}}},
   {"sender":"175","time":15,"message":"update next","response":{"recipient":{"id":"17"},"message":{"text":"this will be updated next."}}},
   {"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Anything else you want to ask me?"}}}
 ]

下面提供了一个示例代码:

<?php

    $json = file_get_contents('items.json');
    $json_as_array = json_decode($json, true);

    $found = null;


    foreach ($json_as_array as $key => $item) 
    {
        if(strtolower($item['message']) == "update next" && $item['response']['recipient']['id'] == 17)
        { 
            $found = $key;
        }
    }


    $json_as_array[$found] = ["sender" => 175, "time" => 15, "message" => "office app", "response" => [ "recipient" => ["id" => 17], "message" => ["text" => "Meanwhile, please wait for our representative to get back to you."]]];


    $json_output = json_encode($json_as_array);
    file_put_contents('items.json', $json_output);


    echo "Done!";

?>

推荐阅读