Php add key value to json object

To add a key-value pair to a JSON object using PHP, you can follow these steps:

  1. Create a JSON string representing the object.
  2. Use the json_decode() function to decode the JSON string into a PHP object.
  3. Add a new key-value pair to the PHP object.
  4. Encode the PHP object back into a JSON string using the json_encode() function.

Here’s an example to illustrate this process:

country = "USA";

// Step 4: Encode the PHP object back into a JSON string
$newJsonString = json_encode($phpObject);

// Output the updated JSON string
echo $newJsonString;
?>

In this example, we start with a JSON string representing an object with three properties: “name”, “age”, and “city”. We use the json_decode() function to decode it into a PHP object. Then, we add a new property called “country” with the value “USA” to the PHP object. Finally, we use the json_encode() function to encode the updated PHP object back into a JSON string, and output it. The result will be:

{
   "name":"John",
   "age":30,
   "city":"New York",
   "country":"USA"
}

Note that if the original JSON string represents an array instead of an object, you would use the same steps but with PHP arrays instead of objects. The syntax for adding a new element to a PHP array is $phpArray[] = value;.

Leave a comment