<?php
// Create the objects here
$objects = [];
$object1 = new stdClass();
$object1->id = 1;
$object1->name = 'Demo Account';
$object1->email = 'demo@localhost.com';
$object2 = new stdClass();
$object2->id = 2;
$object2->name = 'Admin Account';
$object2->email = 'admin@localhost.com';
// Add objects to the array
$objects[] = $object1;
$objects[] = $object2;
// Transform the array into a JSON object
$encodedJson = json_encode($objects, JSON_PRETTY_PRINT);
// Output the JSON object for demonstration purposes
print "Encoded JSON string\r\n" . $encodedJson . "\r\n\r\n";
// Decode the JSON object for demonstration purposes
$decodedJson = json_decode($encodedJson);
// Loop through the decoded JSON object
foreach($decodedJson AS $json) {
print 'Id: ' . $json->id;
print "\r\n";
print 'Name: ' . $json->name;
print "\r\n";
print 'Email: ' . $json->email;
print "\r\n";
}
That returns
Encoded JSON string
[
{
"id": 1,
"name": "Demo Account",
"email": "demo@localhost.com"
},
{
"id": 2,
"name": "Admin Account",
"email": "admin@localhost.com"
}
]
Id: 1
Name: Demo Account
Email: demo@localhost.com
Id: 2
Name: Admin Account
Email: admin@localhost.com
So if you wanted to get say the 2nd userâs email only, you can put something like
if($key == 1) {
print 'Email: ' . $json->email;
print "\r\n";
} else {
... Do something else
}
Where $key
is the index of that array object or you can even do if you want to be consistent and use the object itself rather than the index key.
if($json->id == 2) {
print 'Email: ' . $json->email;
print "\r\n";
} else {
... Do something else
}
This is by âfarâ the best and easiest way to work with JSON strings in PHP because youâre not trying to do random regexs or even random modifications on the JSON string itself. If you wanted more fields added to that JSON string, all you need to do is add those fields to the $object1
or $object2
variables.
In the case youâre talking about, all you would do is something along the lines of
$decodeJson = json_decode($encodedJsonStringHere);
print $decodeJson->email;
And if you wanted to replace that value, you overwrite the value and then encode back into a JSON string. Simple as that.
So something like
$decodeJson = json_decode($encodedJsonStringHere);
// Old email
print $decodeJson->email; // returns demo@localhost.com if we were targeting the first object in the array, if not then it would return all emails if this was used in the foreach loop
$decodeJson->email = 'NewEmail@email.com';
// New email
print $decodeJson->email; // returns NewEmail@email.com