How to decode a JSON String with several objects in PHP?
New answer
Re your revised question: foreach
actually works with properties as well as with many-valued items (arrays), details here. So for instance, with the JSON string in your question:
$data = json_decode($json);
foreach ($data as $name => $value) {
// This will loop three times:
// $name = inbox
// $name = sent
// $name = draft
// ...with $value as the value of that property
}
Within your main loop over the properties, you can use an inner loop to go over the array entries each property points to. So for instance, if you know that each of the top-level properties has an array value, and that each array entry has a "firstName" property, this code:
$data = json_decode($json);
foreach ($data as $name => $value) {
echo $name . ':'
foreach ($value as $entry) {
echo ' ' . $entry->firstName;
}
}
...will show:
inbox:
Brett
Jason
Elliotte
sent:
Issac
Tad
Frank
draft:
Eric
Sergei
Old answer(s)
Begin edit
Re your comment:
Now I would like to know how to decode JSON string with several objects!
The example you posted does have several objects, they're just all contained within one wrapper object. This is a requirement of JSON; you cannot (for example) do this:
{"name": "I'm the first object"},
{"name": "I'm the second object"}
That JSON is not valid. There has to be a single top-level object. It might just contain an array:
{"objects": [
{"name": "I'm the first object"},
{"name": "I'm the second object"}
]}
...or of course you can give the individual objects names:
{
"obj0": {"name": "I'm the first object"},
"obj1": {"name": "I'm the second object"}
}
End edit
Your example is one object containing three properties, the value of each of which is an array of objects. In fact, it's not much different from the example in the question you linked (which also has an object with properties that have array values).
So:
$data = json_decode($json);
foreach ($data->programmers as $programmer) {
// ...use $programmer for something...
}
foreach ($data->authors as $author) {
// ...use $author for something...
}
foreach ($data->musicians as $musician) {
// ...use $musician for something...
}
decode json array with multiple objects in php
Use json_decode()
to decode a JSON string, like this:
$json_array = json_decode($json, true);
^ When TRUE, returned objects will be converted into associative arrays.
So your code should be like this:
// Here $json is your json string
$json_array = json_decode($json, true);
foreach($json_array as $key => $arrays){
echo $key . "<br />";
foreach($arrays as $array){
foreach($array as $key => $value){
echo $key . " => " . $value . "<br />";
}
}
echo "<br />";
}
Output:
article_details
article_code => 000000000300028156
diff_amnt => 1
article_code => 000000000300028174
diff_amnt => 1
article_code => 000000000300028126
diff_amnt => 1
article
article_code => 000000000300028156
diff_amnt => 1
article_code => 000000000300028174
diff_amnt => 1
article_code => 000000000300028126
diff_amnt => 1
Decoding multiple JSON objects in PHP
tidy your input, add commas after every json string, send like this:
{ "m_time" : "2015-04-07 11:37:35", "id" : "30", "msg" : "Hai there 1"},{ "m_time" : "2015-04-07 11:37:36", "id" : "31", "msg" : "Hai there 2"},{ "m_time" : "2015-04-07 11:37:37", "id" : "32", "msg" : "Hai there 3"},
php function
function json_decode_multi($s, $assoc = false, $depth = 512, $options = 0) {
if(substr($s, -1) == ',')
$s = substr($s, 0, -1);
return json_decode("[$s]", $assoc, $depth, $options);
}
var_dump(json_decode_multi('{ "m_time" : "2015-04-07 11:37:35", "id" : "30", "msg" : "Hai there 1"},{ "m_time" : "2015-04-07 11:37:36", "id" : "31", "msg" : "Hai there 2"},{ "m_time" : "2015-04-07 11:37:37", "id" : "32", "msg" : "Hai there 3"},'));
output:
array(3) {
[0] =>
class stdClass#1 (3) {
public $m_time =>
string(19) "2015-04-07 11:37:35"
public $id =>
string(2) "30"
public $msg =>
string(11) "Hai there 1"
}
[1] =>
class stdClass#2 (3) {
public $m_time =>
string(19) "2015-04-07 11:37:36"
public $id =>
string(2) "31"
public $msg =>
string(11) "Hai there 2"
}
[2] =>
class stdClass#3 (3) {
public $m_time =>
string(19) "2015-04-07 11:37:37"
public $id =>
string(2) "32"
public $msg =>
string(11) "Hai there 3"
}
}
Keep in mind: the protocol design is not stable. @socket_recv($changed_socket, $buf, READ_SIZE, 0)
may read half a string(broken) if it meets max READ_SIZE. If the data decoding failed, you should keep the last received data, and read more data to append to it and retry.
php json decode object with array of multiple objects
$myArray = json_decode($json, true);
var_dump($myArray['id']);
var_dump($myArray['user'][0]['fname']);
How to convert a string to JSON object in PHP
What @deceze said is correct, it seems that your JSON is malformed, try this:
{
"Coords": [{
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778339",
"Longitude": "-9.0121466",
"Timestamp": "Fri Jun 28 2013 11:45:54 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778159",
"Longitude": "-9.0121201",
"Timestamp": "Fri Jun 28 2013 11:45:58 GMT+0100 (IST)"
}]
}
Use json_decode
to convert String into Object (stdClass
) or array: http://php.net/manual/en/function.json-decode.php
[edited]
I did not understand what do you mean by "an official JSON object", but suppose you want to add content to json via PHP and then converts it right back to JSON?
assuming you have the following variable:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
You should convert it to Object (stdClass):
$manage = json_decode($data);
But working with stdClass
is more complicated than PHP-Array, then try this (use second param with true
):
$manage = json_decode($data, true);
This way you can use array functions: http://php.net/manual/en/function.array.php
adding an item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
echo '<br>After: <br>';
print_r($manage);
remove first item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
array_shift($manage['Coords']);
echo '<br>After: <br>';
print_r($manage);
any chance you want to save to json to a database or a file:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
$manage = json_decode($data, true);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
if (($id = fopen('datafile.txt', 'wb'))) {
fwrite($id, json_encode($manage));
fclose($id);
}
Decoding multiple JSON responses using PHP
First check that you are recieving output from var_dump(file_get_contents($url))
.
Then verify that the string returned is valid JSON. Explained here by Nordenheim
Once you can confirm its valid, inspect the JSON decoded data to see how to access the correct value.
var_dump(json_decode(file_get_contents($url)));
so the following should be what your looking for;
$data = json_decode(file_get_contents($url));
;
echo $data['data'][0]['id'];
Split Json object into multiple json objects in PHP
Try this loop over each record and save it in result.
$json=json_decode($str,true);
array_map(function($value) use (&$results){
$results[$value['id']]=json_encode($value['items']);
return $results;
}
,$json['results']);
print_r($results);
output
Array (
[001] => {"item11":"value1","item12":"value2","item13":"value3"}
[002] => {"item21":"value1","item22":"value2","item23":"value3"}
[003] => {"item31":"value1","item32":"value2","item33":"value3"} )
How to decode multi-layers nested JSON String and display in PHP?
The JSON you provided (in your question) is malformed and using json_decode()
on it will result in NULL
. Thus nothing will happen when you try to access the decoded object because it doesn't exist.
The full JSON you provided is valid and the reason why your code didn't yield any results is because in items
there is an "inner"-array:
(...)
["items"] => array(1) {
[0] => array(4) {
// ^^^^^^^^^^^^^^^^^
["update_timestamp"] => string(25) "2017-05-02T09:21:18+08:00"
["timestamp"] => string(25) "2017-05-02T09:07:00+08:00"
["valid_period"] => array(2) {
["start"] => string(25) "2017-05-02T09:00:00+08:00"
["end"] => string(25) "2017-05-02T11:00:00+08:00"
}
["forecasts"] => array(47) {
[0] => array(2) {
["area"] => string(10) "Ang Mo Kio"
["forecast"] => string(19) "Partly Cloudy (Day)"
}
(...)
You'll have to access that array through key 0
, for arrays it will look like this:
$data = json_decode($json, true);
echo $data['items'][0]['forecasts'][0]['area'];
// ^^^
And for objects like this:
$data = json_decode($json);
echo $data->items[0]->forecasts[0]->area;
// ^^^
The second 0
changes the location (the different arrays in the forecasts
array).
You can check the output here (array approach) and here (object approach).
PHP: Read JSON file with multiple objects in array and split by objects
Decode then encode:
$str = '[{"color":1,"blocks":[[{"id":64}]]},{"color":1,"blocks":[[{"id":64},{"id":64}],[{"id":1}]]},{"color":2,"blocks":[[{"id":64},{"id":64}],[{"id":1}]]}]';
$config = json_decode($str, true);
$json = json_encode($config[2]);
print $json;
This will print what you want.
Related Topics
Stream_Socket_Client Unable to Connect (Connection Timed Out)
Bulk Rename Files in a Folder - PHP
Soft Delete Best Practices (Php/Mysql)
PHP - Cannot Use a Scalar as an Array Warning
500 Server Error: Premature End of Script Headers:
Work-Around for PHP5's Pdo Rowcount MySQL Issue
How to Protect HTML Form from Spammers
How to Execute and Get Content of a .PHP File in a Variable
Day of the Week to Day Number (Monday = 1, Tuesday = 2)
[PHP Warning: Mail(): " Sendmail_From" Not Set in PHP.Ini or Custom "From:" Header Missing
Laravel Orm from Self Referencing Table Get N Level Hierarchy JSON
Laravel Form HTML with Put Method for Put Routes
Google API How to Connect to Receive Values from Spreadsheet
Enabling Cors in Codeigniter ( Restserver by @Chriskacerguis )
How to Get the External Ip of My Server Using PHP
Recreate Original PHP Array from Print_R Output
Imagecreatefromjpeg and Similar Functions Are Not Working in PHP