Home > Mobile >  Changing the value of one key/value pair in a json file with PHP
Changing the value of one key/value pair in a json file with PHP

Time:05-24

We have a simple json file that we use store data and are trying to figure out how to manipulate the value for one key and then save the new value in said json file using PHP.

The json file is basically:

{
  "stuff":"something",
  "more":"whatever",
  "name":"George",
  "about":"some string",
  "when":"tomorrow",
  many more key/value pairs
}

We want to get the 'about' string, append another string to it and then save the resultant longer string. Getting the data and appending the additional string is not an issue. It is saving the new string that has me stumped.

$data = json_decode($json);
foreach ($data as $key => $value) { 
  // look for about data
  if ($key == 'about') {
    $newstr = $value;
    $newstr .= ' extra string bits';
     
    // need to replace original $value with $newstr
    
  }
}

$newjson = json_encode($data);

The resultant json should be:

{
  "stuff":"something",
  "more":"whatever",
  "name":"George",
  "about":"some string extra string bits",
  "when":"tomorrow",
  many more key/value pairs
}

We are using the foreach as other values from the json file are being used in the PHP process, but if there is another better way to deal with the data retrieval and update portion, I am happy to separate the functions and welcome suggestions.

CodePudding user response:

No need to use foreach. When you json_decode your JSON you can simply set the objects new value by appending to it:

<?php
$json = '{
  "stuff":"something",
  "more":"whatever",
  "name":"George",
  "about":"some string",
  "when":"tomorrow"
}';
$data = json_decode($json);
$data->about .= ' extra string bits';
echo json_encode($data, JSON_PRETTY_PRINT);

will output:

{
    "stuff": "something",
    "more": "whatever",
    "name": "George",
    "about": "some string extra string bits",
    "when": "tomorrow"
}

CodePudding user response:

here is:

$data = json_decode($json,true);
foreach ($data as $key => $value) { 
  // look for about data
  if ($key == 'about') {
    $newstr = $value;
    $newstr .= ' extra string bits';
    $data[$key] = $newstr;
  }
}

$newjson = json_encode($data);
  • Related