Decoding JSON SubArray PHP - php

I have looked around on Google for quite some time now, and I'm unable to find a solution that works for me.
I have this JSON Array:
[
{
"id": 1000,
"userIdent": "ABC1000",
"username": "john.doe",
"contacts": [
{
"id": 2000,
"clientId": 1000,
"email": "john.doe#example.com",
"phone": "",
"name": "",
"isBilling": false,
"isContact": false,
"types": [
{
"id": 3000,
"name": "Home contact"
}
]
}
]
}
]
and I have this PHP code:
$json = json_decode($response, true);
foreach($json as $item) {
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
echo $item['contacts']['phone'] . "<br><br>";
foreach($json->contacts as $contacts) {
echo $contacts->phone;
echo $contacts['contacts']['phone'];
}
}
I have tried:
$item['contacts']['phone'];
$contacts->phone;
$contacts['contacts']['phone'];
I can't seem to be able to full any of the data from the sub-array "contacts". Any help would be greatly appreciated!

Note:- When you use true while using json_decode() it converts all json data to array(inner or outer). So you need to treat contacts as an array not an object.
So You need to iterate over $item['contacts'] array in the second foreach()
Do like below:-
$json = json_decode($response, true);
foreach($json as $item) {
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
foreach($item['contacts'] as $contacts) {//treat contacts as an array not as an object
echo $contacts['phone'];
}
}
Output:- https://eval.in/952121 (i have taken phone number for testing purpose)

You have made a mistake, on your json, the contacts property is an array, so you can't access it (either in javascript or php) as an object with $contacts->contacts['phone'].
You should do something like that : $contacts->contacts[0]['phone'] or iterate other each contacts if there may be many.

Your code should look more like this
foreach($json as $item) { // 1
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
foreach($item['contacts'] as $contact) { // 2
echo $contact['phone'];
}
}
So in the first foreach you start iterating over you entire array of items (1). Inside an item is an array contacts, so you start iterating over that with a new foreach (2). Each contact can be accessed directly inside the inner foreach.
Also, on decoding you said you wanted an array as output, so you should expect that and always access it like an array (square braces). If you would have gone for an object, the $contacts->phone syntax would work, but you shouldn't mix them like you are doing.
I hope this makes sense. Feel free to ask if not.

Related

Reading Json object with inside array

This is my JSON result:
{
"#odata.context": "http://wabi-west-europe-redirect.analysis.windows.net/v1.0/collections/washington/workspaces/37380bc1-dd47-4c95-8dbd-5efecafc8b26/$metadata#reports",
"value": [
{
"id": "6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"modelId": 0,
"name": "america",
"webUrl": "https://app.powerbi.com/reports/6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"embedUrl": "https://embedded.powerbi.com/appTokenReportEmbed?reportId=6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"isOwnedByMe": true,
"isOriginalPbixReport": false,
"datasetId": "3f1f480c-4a8c-4756-87eb-fc29f5d76de3"
},
{
"id": "ce558be6-aaf9-4bee-b344-6db7754e572b",
"modelId": 0,
"name": "dency",
"webUrl": "https://app.powerbi.com/reports/ce558be6-aaf9-4bee-b344-6db7754e572b",
"embedUrl": "https://embedded.powerbi.com/appTokenReportEmbed?reportId=ce558be6-aaf9-4bee-b344-6db7754e572b",
"isOwnedByMe": true,
"isOriginalPbixReport": false,
"datasetId": "5264cf84-214a-4c33-8f8e-f421d8ce1846"
}
]
}
In PHP im getting into
$response = json_decode($aboveresult);
But My problem is the value is in array.I want to get both the array value like id,modelId,Name,...
Please help me.
I tried $response['value'].But its showing error like Cannot use object of type stdClass as array
json_decode() accepts a second parameter, which is by default false. If you pass true, the function will return you an associative array instead of an instance of stdClass and you can work with it the way you tried before.
You have to change:
$response = json_decode($aboveresult,true);
When you mentioned the second parameter as true you will get the ASSOCIATIVE array
Try this
echo "<pre>";
$json_data = json_decode($json); //$json = your json string
print_r($json_data->value);
foreach($json_data->value as $value) {
echo 'ID: '.$value->id .'<br>';
echo 'modelId: '.$value->modelId .'<br>';
echo 'name: '.$value->name .'<br>';
}

Php loop with json coming back empty

what am i doing wrong here?
when i have only One result coming back this code works perfectly
$someObject = json_decode($data);
$id=$someObject->clips[0]->id;
but when i want to do a loop because i may get back 10 results this code is not working, i am sure i am missing something very simple here
$someObject = json_decode($data);
//var_dump($someObject);
foreach($someObject as $json){
echo $json->clips[0]->id;
}
EDIT:
this solution worked for anyone else who comes looking
foreach ($someObject->clips as $clip){
echo $clip->id. "<br>";
}
not sure how the other one answers the for loop issue i was having however.
You need to change this index [0] to dynamic index.
foreach($someObject as $k => $json){
echo $json->clips[$k]->id; // Insert $k here
}
change this
foreach($someObject as $json){
echo $json->clips[0]->id;
}
to
$i=0;
foreach($someObject as $json){
echo $json->clips[$i]->id;
$i++;
}
or as miken32 stated in the comment
foreach ($someObject->clips as $clip){
echo $clip->id;
}
read this reference: control-structures.foreach.php
in php array if you want to get all of items iterate you can use foreach
imaging you have this sample json:
{
"clips": [{
"id": 1,
"name": "test",
"tags": [
"tag1",
"tag2",
"tag3"
]
},
{
"id": 2,
"name": "test2",
"tags": [
"tag4",
"tag5",
"tag6"
]
}
]
}
if you want to get clips and tag list you can use this code:
<?php
$jsonText = '{"clips": [{"id": 1,"name": "test","tags": ["tag1","tag2","tag3"]},{"id": 2,"name": "test2","tags": ["tag4","tag5","tag6"]}]}';
$jsonObj = json_decode($jsonText);
// in this loop you can get clipObject
foreach($jsonObj->clips as $clipObj){
echo "clip id:" . $clipObj->id . "<br>\n";
echo "clip name:" . $clipObj->name. "<br>\n";
// in this loop you can get tags
foreach($clipObj->tags as $tag){
echo "clip tag:" . $tag. "<br>\n";
}
}

Issues with decoding json object

Thanks for your time in reading this post.
My php file is receiving a json object. But I am facing issues while decoding it.
My php code:
$data=$_POST['arg1'];
echo $data;
$json = json_decode($data,true);
echo $json;
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
When I echo data results as below.
{
"SCI-2": {
"quantity": 2,
"id": "SCI-2",
"price": 280,
"cid": "ARTCOTSB"
}
}
When I echo $json, result is as it follows :
Array
Name1 : Array.
Please assist as i need tho access the cid and quantity values in the $data.
json_decode returns an array. And to print array you can use print_r or var_dump.
Now to access your values you can try :
$json["SCI-2"]["quantity"] for quantity and $json["SCI-2"]["cid"] for cid.
Demo : https://eval.in/522350
To access in foreach you need this :
foreach($json as $k) {
foreach($k as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
}
}
Since you do not know the number of items in your object, use this:
$obj = json_decode($json);
After this, iterate the $obj variable and after that, inside the loop, use the foreach to get each property.
foreach($iteratedObject as $key => $value) {
//your stuff
}

How to loop over and access various elements in an array that is both multidimentional and associative? PHP, either JSON or XML

I'm retrieving bibliographic data via an API (zotero.org), and it is similar to the sample at the bottom (just way more convoluted - sample is typed).
I want to retrieve one or more records and display certain values on the page. For example, I would like to loop through each top level record and print the data in a nicely formated citation. Ignoring the proper bib styles for the moment, let's say I want to just print out the following for each record returned:
author1 name, author2 name, article title, publication title, key
This doesn't match the code, because I've clearly been referencing the key value pairs incorrectly and will just make a mess of it.
The following is laid out like the data if I request JSON format, though I can request XML data instead. I'm not picky; I've tried using each with no luck.
[
{
"key": "123456",
"state": 100,
"data": {
"articleTitle": "Wombat coprogenetics: enumerating a common wombat population by microsatellite analysis of faecal DNA",
"authors": [
{
"firstName": "Sam C.",
"lastName": "Smith"
},
{
"firstName": "Maxine P.",
"lastName": "Jones"
}
],
"pubTitle": "Australian Journal of Zoology",
"tags": [
{
"tag": "scary"
},
{
"tag": "secret rulers of the world"
}
]
}
},
{
"key": "001122",
"state": 100,
"data": {
"articleTitle": "WOMBAT and WOMBAT-PK: Bioactivity Databases for Lead and Drug Discovery",
"authors": [
{
"firstName": "Marius",
"lastName": "Damstra"
}
],
"pubTitle": "Chemical Biology: From Small Molecules to Systems Biology",
"tags": [
{
"tag": "Wrong Wombat"
}
]
}
}
]
If there is a mistake in brackets, commas, etc. it is just a typo in my example and not the cause of my issue.
decode your json as array and iterate it as any array as flowing:
$json_decoded= json_decode($json,true);
$tab="\t";
foreach ($json_decoded as $key => $val) {
echo "Article ".$val["key"]."\n" ;
echo $tab."Authors :\n";
foreach ($val["data"]["authors"] as $key => $author){
echo $tab.$tab. ($key+1) ." - ".$author["firstName"]. " ".$author["lastName"]."\n";
}
echo $tab."Article Title: ".$val["data"]["articleTitle"] ."\n";
echo $tab."Publication Title: ".$val["data"]["pubTitle"] ."\n";
echo $tab."Key: ".$val["key"]."\n";
}
run on codepad
and you can use the same method for xml as flowing:
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$json_decoded = json_decode($json,TRUE);
//the rest is same
for xml you can use the SimpleXml's functions
or DOMDocument class
Tip
to know the structure of your data that api return to you after it converted to array use var_dump($your_decoded_json) in debuging
Something like this might be a good start for you:
$output = [];
// Loop through each entry
foreach ($data as $row) {
// Get the "data" block
$entry = $row['data'];
// Start your temporary array
$each = [
'article title' => $entry['articleTitle'],
'publication title' => $entry['pubTitle'],
'key' => $row['key']
];
// Get each author's name
foreach ($entry['authors'] as $i => $author) {
$each['author' . ++$i . ' name'] = $author['firstName'] . ' ' . $author['lastName'];
}
// Append it to your output array
$output[] = $each;
}
print_r($output);
Example: https://eval.in/369313
Have you tried to use array_map ?
That would be something like:
$entries = json_decode($json, true);
print_r(array_map(function ($entry) {
return implode(', ', array_map(function ($author) {
return $author['firstName'];
}, $entry['data']['authors'])) . ', ' . $entry['data']['articleTitle'] . ', ' . $entry['key'];
}, $entries));

Get data from JSON file with PHP [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
I'm trying to get data from the following JSON file using PHP. I specifically want "temperatureMin" and "temperatureMax".
It's probably really simple, but I have no idea how to do this. I'm stuck on what to do after file_get_contents("file.json"). Some help would be greatly appreciated!
{
"daily": {
"summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.",
"icon": "clear-day",
"data": [
{
"time": 1383458400,
"summary": "Mostly cloudy throughout the day.",
"icon": "partly-cloudy-day",
"sunriseTime": 1383491266,
"sunsetTime": 1383523844,
"temperatureMin": -3.46,
"temperatureMinTime": 1383544800,
"temperatureMax": -1.12,
"temperatureMaxTime": 1383458400,
}
]
}
}
Get the content of the JSON file using file_get_contents():
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode():
$json = json_decode($str, true); // decode the JSON into an associative array
You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:
echo '<pre>' . print_r($json, true) . '</pre>';
This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
Demo!
Use json_decode to transform your JSON into a PHP array. Example:
$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b
Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}

Categories