php - 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?"}}}
我想根据两个标准更新第三条记录:
- “身份证”:“17”
- “消息”:“下一个更新”
我想要的第三条记录的输出 -
{"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更新记录。
解决方案
首先,您需要创建一个有效的 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!";
?>
推荐阅读
- java - Leetcode - 检查 N 和它的双精度是否存在
- python - 如何组合和平均数据框矩阵中的值?
- python - Python:查找数组中第一个零实例的索引,如果没有找到返回无
- html - 使用 css 删除 div 和 table 之间的空间
- python - Python 请求包中带有 GET 请求的代理
- javascript - 当搜索栏退格为空时,如何让我的列表不显示?
- javascript - 通过 JavaScript 添加内容的 div 的宽度为 0
- python - 如何使用python从JSON中删除特定成员
- javascript - 在 TypeScript 中使用枚举指定类型的替代方法?
- powershell - Powershell替换一个文件夹中多个文件中的文本