First of all, you need to make a valid JSON
then you have to convert the JSON to an array
then you have to iterate through the array and find which item matches the criteria
and last you change the values.
JSON file content (filename: 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?"}}}
]
an example code is provided below:
<?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
solved php update json data based on criteria