php根据标准更新json数据

时间:2018-06-17 14:39:27

标签: 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. " ID":" 17"
  2. " message":" next next"
  3. 我想要的第三条记录的输出 -

    {"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更新记录。

2 个答案:

答案 0 :(得分:0)

首先,您需要制作有效的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!";

?>

答案 1 :(得分:0)

我不会写所有的代码,但存储json的正确方法,我的方式是

file_put_contents('appendData.txt', json_encode($inRadiusPostalCodes) , FILE_APPEND | LOCK_EX);

接下来当你阅读文件时,只需用

读取文件
file_get_contents();

将其存储在变量中,然后对字符串进行json_decode,然后循环遍历数组以更新所需索引的记录,如

if($index == $someindex){......}