I have nested JSON in PHP, I am new to PHP and I am unable to read the below-nested JSON. Here is the long JSON file.
<?php
$nestedjson='{
"value": [
{
"name": "POOL1",
"id": "/subscriptions/2xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/hostpools/AZREUSLSHP1",
"type": "Microsoft.DesktopVirtualization/hostpools",
"location": "eastus",
"tags": {
"owner": "Domain",
"department": "TPW",
"workLoadType": "WVD",
"contactName": "testuser1",
"CostBucket": "bucket1"
},
"kind": null,
"properties": {
"friendlyName": null,
"description": "Created through the WVD extension",
"hostPoolType": "Pooled",
"personalDesktopAssignmentType": null,
"applicationGroupReferences": [
"/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/applicationgroups/AZREUSLSHP1-DAG",
"/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/applicationgroups/AZREUSFINGRP"
],
"customRdpProperty": "",
"maxSessionLimit": 6,
"loadBalancerType": "BreadthFirst",
"validationEnvironment": false,
"ring": null,
"registrationInfo": {
"expirationTime": null,
"token": null,
"resetToken": false,
"registrationTokenOperation": "None"
},
"vmTemplate": "{\"domain\":\"XXXX\",\"galleryImageOffer\":null,\"galleryImagePublisher\":null,\"galleryImageSKU\":null,\"imageType\":\"CustomImage\",\"imageUri\":null,\"customImageId\":\"/subscriptions/XXXX/resourceGroups/IMAGEGALLERYRG/providers/Microsoft.Compute/galleries/WVDImageGallery3/images/WVDBaseImageDefinition1\",\"namePrefix\":\"AZREUSWVD\",\"osDiskType\":\"StandardSSD_LRS\",\"useManagedDisks\":true,\"vmSize\":{\"id\":\"Standard_B2ms\",\"cores\":2,\"ram\":8},\"galleryItemId\":null}",
"preferredAppGroupType": "Desktop",
"migrationRequest": null,
"cloudPcResource": false,
"startVMOnConnect": false,
"ssoadfsAuthority": null,
"ssoClientId": null,
"ssoClientSecretKeyVaultPath": null,
"ssoSecretType": null,
"objectId": "3a5db190-342d-441e-9798-667079784cbf"
}
},
{
"name": "POOL2",
"id": "/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/hostpools/AZREUSLSHP2",
"type": "Microsoft.DesktopVirtualization/hostpools",
"location": "eastus",
"tags": {
"owner": "Domain",
"department": "TPW",
"workLoadType": "WVD",
"contactName": "testuser2",
"CostBucket": "bucket2"
},
"kind": null,
"properties": {
"friendlyName": null,
"description": "Created through the WVD extension",
"hostPoolType": "Personal",
"personalDesktopAssignmentType": "Direct",
"applicationGroupReferences": [
"/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/applicationgroups/AZREUSLSHP2-DAG"
],
"customRdpProperty": "",
"maxSessionLimit": 999999,
"loadBalancerType": "Persistent",
"validationEnvironment": false,
"ring": null,
"registrationInfo": {
"expirationTime": null,
"token": null,
"resetToken": false,
"registrationTokenOperation": "None"
},
"vmTemplate": "{\"domain\":\"domain.com\",\"galleryImageOffer\":\"Windows-10\",\"galleryImagePublisher\":\"microsoftwindowsdesktop\",\"galleryImageSKU\":\"19h2-ent-g2\",\"imageType\":\"Gallery\",\"imageUri\":null,\"customImageId\":null,\"namePrefix\":\"AZREUSWVDP\",\"osDiskType\":\"StandardSSD_LRS\",\"useManagedDisks\":true,\"vmSize\":{\"id\":\"Standard_B2s\",\"cores\":2,\"ram\":4},\"galleryItemId\":\"microsoftwindowsdesktop.windows-1019h2-ent-g2\"}",
"preferredAppGroupType": "Desktop",
"migrationRequest": null,
"cloudPcResource": false,
"startVMOnConnect": false,
"ssoadfsAuthority": null,
"ssoClientId": null,
"ssoClientSecretKeyVaultPath": null,
"ssoSecretType": null,
"objectId": "d187b18a-baa7-4e59-97ad-f84a1f50186e"
}
},
{
"name": "POOL3",
"id": "/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/AZREUSLSWVDREFRG/providers/Microsoft.DesktopVirtualization/hostpools/ReferenceHostPool",
"type": "Microsoft.DesktopVirtualization/hostpools",
"location": "eastus",
"tags": null,
"kind": null,
"properties": {
"friendlyName": null,
"description": null,
"hostPoolType": "Pooled",
"personalDesktopAssignmentType": null,
"applicationGroupReferences": [
"/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/AZREUSLSWVDREFRG/providers/Microsoft.DesktopVirtualization/applicationgroups/RefAppGroup"
],
"customRdpProperty": "",
"maxSessionLimit": 5,
"loadBalancerType": "DepthFirst",
"validationEnvironment": false,
"ring": null,
"registrationInfo": {
"expirationTime": null,
"token": null,
"resetToken": false,
"registrationTokenOperation": "None"
},
"vmTemplate": null,
"preferredAppGroupType": "Desktop",
"migrationRequest": null,
"cloudPcResource": false,
"startVMOnConnect": false,
"ssoadfsAuthority": null,
"ssoClientId": null,
"ssoClientSecretKeyVaultPath": null,
"ssoSecretType": null,
"objectId": "1f06e1c3-669e-4227-bb7c-386b634c6c30"
}
}
],
"nextLink": null
}'
I would like to read and print the values of "hostPoolType" from the above JSON, I have tried the below code it didn't work.
$arr = json_decode($nestedjson, true);
$hostpooltype = $arr['properties']['hostPoolType'];
//print_r($hostpooltype);
foreach($hostpooltype as $item)
{
echo $item;
echo '<br>';
}
?>
It's not returning the correct result. Can anyone please help here?
you should run loop for each value key of json array.
use this.
<?php
$arr = json_decode($nestedjson, true);
foreach ($arr['value'] as $newArr){
echo $newArr['properties']['hostPoolType'];
echo '<br>';
}
?>
I have found the solution here.
$arr = json_decode($nestedjson, true);
$hostpooltype = array();
$names = array();
foreach ($arr['value'] as $newArr)
{
$hostpooltype[] = $newArr['properties']['hostPoolType'];
$names[] = $newArr ['name'];
}
// Print the values of the A
foreach($hostpooltype as $value){
echo $value . "<br>";
}
Try to use array_walk function:
$arr = json_decode($nestedjson);
function recursiveWalk($value, $key)
{
if (is_array($value)) {
array_walk($value, "recursiveWalk");
}
if (is_object($value)) {
echo "{$value->properties->hostPoolType}<br>";
}
}
array_walk($arr, "recursiveWalk");
Related
I was hoping that I would be able to do it, but again I ran into something where I am powerless...
Please help me with a solution. After the call I get a JSON Response. I decode the response and read individual fields from "data".
But I came across the EAN and PLU fields where the field looks like
"ean": ["2112244"] and the processing I'm using reads 0 = false or 1 = true from that.
And I don't know how to read it in order to write the EAN of the given product into the database.
Decode response
$data = json_decode($response, true);
foreach($data["data"] as $row){
$categoryid = $row["_categoryId"];
$productid = $row["id"];
$name = $row["name"];
$ean = $row["ean"];
$plu = $row["plu"];
$externalid = $row["externalId"];
$units = $row["unit"];
$unitsmeasurment = $row["unitMeasurement"];
$packaging = $row["packaging"];
$packagingmeasurment = $row["packagingMeasurement"];
}
Json response
"data": [
{
"_categoryId": "415874342455239",
"_cloudId": "349305323",
"_defaultCourseId": null,
"_eetSubjectId": null,
"_supplierId": null,
"allergens": [],
"alternativeName": null,
"created": "2023-01-25T12:39:57.19Z",
"currency": "CZK",
"deleted": false,
"deliveryNoteIds": null,
"description": null,
"discountPercent": "0",
"discountPermitted": true,
"display": true,
"ean": ["54544844544"],
"externalId": null,
"features": [],
"flags": "4096",
"hexColor": "#623320",
"id": "200915715273883",
"imageUrl": null,
"margin": null,
"marginMin": null,
"modifiedBy": "411782225143287",
"name": "Americano",
"notes": null,
"onSale": false,
"packageItem": "1",
"packaging": "1",
"packagingMeasurement": "1",
"packagingPriceWithVat": null,
"plu": [],
"points": "0",
"priceInPoints": null,
"priceWithVat": "59",
"priceWithVatB": null,
"priceWithVatC": null,
"priceWithVatD": null,
"priceWithVatE": null,
"priceWithoutVat": "51.30434782608696",
"purchasePriceWithoutVat": null,
"requiresPriceEntry": false,
"sortOrder": "0",
"stockDeduct": true,
"stockOverdraft": "ALLOW",
"subtitle": null,
"supplierProductCode": null,
"tags": null,
"unit": "Piece",
"unitMeasurement": "Piece",
"vat": "1.15",
"versionDate": "2023-01-25T12:39:57.19Z"
},
I don't endorse this in your database schema, but you can create a comma-separated list.
$ean = implode(',', $row["ean"]);
i get a response of my code . that response has a variable value which is before a constant string and after another constant string . i want get this variable and echo it .
example : i have this json:
{ "id": "tok_1Cs0osBsNOaFjmrSIBFEAkPd", "object": "token", "client":
{ "id": "card_1Cs0osBsNOaFjmrSl9fAs5hT", "object": "name", "address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": "74455", "address_zip_check": "unchecked", "country": "RU", "metadata": {}, "name": "2022 Nemelek\r\n", "tokenization_method": null }, "client_ip": "41.199.157.183", "created": 1532578278, "livemode": true, "type": "Uid", "used": false }
i wanna extract tok_1Cs0osBsNOaFjmrSIBFEAkPd which is after { "id": " and before ", "object":
btw : this value is variable but what is before and first word after it are constants
how can i code it in php
Use json_decode():
$str = '{ "id": "tok_1Cs0osBsNOaFjmrSIBFEAkPd", "object": "token", "client": { "id": "card_1Cs0osBsNOaFjmrSl9fAs5hT", "object": "name", "address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": "74455", "address_zip_check": "unchecked", "country": "RU", "metadata": {}, "name": "2022 Nemelek\r\n", "tokenization_method": null }, "client_ip": "41.199.157.183", "created": 1532578278, "livemode": true, "type": "Uid", "used": false }';
$v = json_decode($str);
//tok_1Cs0osBsNOaFjmrSIBFEAkPd
echo $v->id;
So I have a huge JSON chunk of data that I need to parse. It has been converted to a PHP array with json_decode. Below is one element of the data object in the PHP array. There are hundreds of these elements, below is just one:
'{
"data": [
{
"id": 3215,
"user_id": {
"id": 99106,
"name": "Rusty shackleford",
"email": "Rusty.shackleford#company.com",
"has_pic": true,
"pic_hash": "someHash",
"active_flag": true,
"value": 99106
},
"person_id": {
"name": "rusty shackleford",
"email": [
{
"label": "Work",
"value": "rusty shackleford#email.com",
"primary": true
}
],
"phone": [
{
"label": "Fax",
"value": "666-666-6666",
"primary": false
},
{
"label": "main",
"value": "666-666-6666",
"primary": false
},
{
"label": "main",
"value": "666-666-6666",
"primary": true
}
],
"value": 666
},
"org_id": {
"name": "shackleford, Inc.",
"people_count": 23,
"cc_email": "rusty#6theShack.com",
"value": 1013
},
"stage_id": 8,
"title": "rusty\'s Projects",
"value": 0,
"currency": "USD",
"add_time": "2013-01-15 00:00:00",
"update_time": "2015-07-07 14:28:15",
"stage_change_time": "2013-10-30 14:43:09",
"active": true,
"deleted": false,
"status": "open",
"next_activity_date": "2015-07-07",
"next_activity_time": null,
"next_activity_id": 3771,
"last_activity_id": 252,
"last_activity_date": "2013-11-16",
"lost_reason": null,
"visible_to": "3",
"close_time": null,
"pipeline_id": 1,
"won_time": null,
"lost_time": null,
"products_count": null,
"files_count": null,
"notes_count": 21,
"followers_count": 1,
"email_messages_count": null,
"activities_count": 2,
"done_activities_count": 1,
"undone_activities_count": 1,
"reference_activities_count": 0,
"participants_count": 1,
"b98336b40c8420dc2f1401d6451b1b47198eee6d": "",
"17a14a9da9815451ff5ffc669d407e8b0376b06b": 4616,
"3eedd4fd08f44a72d911dc4934a6916f3b31911b": "",
"52ede287f6c55eb6b12821ca24f74098779abdce": "",
"13916ba291ab595f27aefbff8b6c43a3fb467b72": "shackleford LLP",
"6330684838740625ea6a7d260f102a1961b2fae1": "shackleford, Inc.",
"ded823307920bf70cea49c45684148fd295e179a": "",
"ed35f69413af7156058d1081321e7bb227577eef_lat": null,
"ed35f69413af7156058d1081321e7bb227577eef_long": null,
"ed35f69413af7156058d1081321e7bb227577eef_subpremise": null,
"ed35f69413af7156058d1081321e7bb227577eef_street_number": null,
"ed35f69413af7156058d1081321e7bb227577eef_route": null,
"ed35f69413af7156058d1081321e7bb227577eef_sublocality": null,
"ed35f69413af7156058d1081321e7bb227577eef_locality": null,
"ed35f69413af7156058d1081321e7bb227577eef_admin_area_level_1": null,
"ed35f69413af7156058d1081321e7bb227577eef_admin_area_level_2": null,
"ed35f69413af7156058d1081321e7bb227577eef_country": null,
"ed35f69413af7156058d1081321e7bb227577eef_postal_code": null,
"ed35f69413af7156058d1081321e7bb227577eef_formatted_address": null,
"09358ea07e1a1007d24bc068c723bf1f79e8359d": null,
"expected_close_date": null,
"7cce64c3abb5f28a260bc9d6719a43367bae5dfe": null,
"stage_order_nr": 10,
"person_name": "shackleford",
"org_name": "shackleford, Inc.",
"next_activity_subject": "pocket Sand!",
"next_activity_type": "task",
"next_activity_duration": "00:00:00",
"next_activity_note": "",
"formatted_value": "$0",
"weighted_value": 0,
"formatted_weighted_value": "$0",
"rotten_time": null,
"owner_name": "Rusty shackleford",
"cc_email": "rusty+stuff3215#shackleford.com",
"org_hidden": false,
"person_hidden": false
}
]
}'
Below is some of my code so far:
$response = json_decode($json_response, true);
//$ksortResult = ksort($response['data']);
foreach($response as $field){
echo $field;
}
If anyone can help me step through the json object with arrays, I'd greatly appreciate it. Also, I'm trying to sort the data based on keys before I step through it.
The desired output would be like the one below:
id|user_id|person_id|org_id|stage_id|title|value|currency|add_time|update_time|stage_change_time|active|deleted|status|next_activity_date|next_activity_time|next_activity_id|last_activity_id|last_activity_date|lost_reason|visible_to|close_time|pipeline_id|won_time|lost_time|products_count|files_count|notes_count|followers_count|email_messages_count|activities_count|done_activities_count|undone_activities_count|reference_activities_count|participants_count|b98336b40c8420dc2f1401d6451b1b47198eee6d|_17a14a9da9815451ff5ffc669d407e8b0376b06b|_3eedd4fd08f44a72d911dc4934a6916f3b31911b|_52ede287f6c55eb6b12821ca24f74098779abdce|_13916ba291ab595f27aefbff8b6c43a3fb467b72|_6330684838740625ea6a7d260f102a1961b2fae1|ded823307920bf70cea49c45684148fd295e179a ed35f69413af7156058d1081321e7bb227577eef_lat ed35f69413af7156058d1081321e7bb227577eef_long|ed35f69413af7156058d1081321e7bb227577eef_subpremise|ed35f69413af7156058d1081321e7bb227577eef_street_number|ed35f69413af7156058d1081321e7bb227577eef_route|ed35f69413af7156058d1081321e7bb227577eef_sublocality|ed35f69413af7156058d1081321e7bb227577eef_locality|ed35f69413af7156058d1081321e7bb227577eef_admin_area_level_1|ed35f69413af7156058d1081321e7bb227577eef_admin_area_level_2|ed35f69413af7156058d1081321e7bb227577eef_country|ed35f69413af7156058d1081321e7bb227577eef_postal_code|ed35f69413af7156058d1081321e7bb227577eef_formatted_address|_09358ea07e1a1007d24bc068c723bf1f79e8359d|expected_close_date|_7cce64c3abb5f28a260bc9d6719a43367bae5dfe|stage_order_nr|person_name org_name|next_activity_subject|next_activity_type|next_activity_duration|next_activity_note|formatted_value|weighted_value|formatted_weighted_value|rotten_time owner_name|cc_email|org_hidden|person_hidden|user_name|user_email|person_phone_1 person_phone_2|person_phone_3|org_people_count
3215|99106|666|1013|8|rusty's Projects|0|USD|1/15/2013 0:00|7/7/2015 14:28|10/30/2013 14:43|TRUE|FALSE|open|7/7/2015|null|3771|252|11/16/2013|null|3|null|1|null|null|null|null|21|1|null|2|1|1|0|1||4616|||shackleford LLP|shackleford,Inc.||null|null|null|null|null|null|null|null|null|null|null|null|null|null|null|10|shackleford|shackleford, Inc.|pocket Sand!|task|0:00:00||$0|0|$0|0:00:00|Rusty shackleford|rusty+stuff3215#shackleford.com|FALSE|FALSE|Rusty shackleford|Rusty.shackleford#company.com|666-666-6666|666-666-6666|666-666-6666|23
So if I understand correctly you want to flatten the json structure? If that's the case, take a look at look at array_walk_recursive:
http://php.net/manual/en/function.array-walk-recursive.php
Which would look something like this:
$newArray = [];
array_walk_recursive( $formerlyJsonArray,
function($value, $key) use (&$newArray) {
$newArray[$key] = $value;
});
Or take a look at array_reduce:
http://php.net/manual/en/function.array-reduce.php
I am getting a json object as a response from a website, and I am trying to find a match to a string, no matter how deep it is nested. Currently, this works for anything in the first level of the object, but as soon as I try something in the second level it does not seem to work. This is my first attempt at a recursive function, so I may just be thinking about it wrong:
foreach($parseObj as $msg) {
parseBlock($msg,'SEARCH STRING',$refID);
}
function parseBlock($block,$id,&$refID) {
if (isset($block->data->id)) {
echo '<b>Parsing: ' . $block->data->id . ':</b><br/> ';
}
if (isset($block->data->body)) {
if (strpos($block->data->body,$id) !== false) {
echo 'found it - <br/>';
$refID = $block->data->name;
return $refID;
} else {
echo 'not here<br/>';
}
}
if (isset($block->data->children)) {
foreach($block->data->children as $msg) {
parseBlock($msg,$id,$refID);
}
}
if (isset($block->data->replies->data->children)) {
foreach($block->data->replies->data->children as $msg) {
parseBlock($msg,$id,$refID);
}
}
}
When the item I want is nested 2nd level or deeper, it finds the ID just fine with this line:
echo '<b>Parsing: ' . $block->data->id . ':</b><br/> ';
And I know the string I want ('SEARCH STRING') is listed there because I can see it in a browser, but it tells me "not here"
When it is on the first nesting level, it responds "found it"
How can I make this work for the deeper nested levels?
Here is an example of the JSON object when the item is nested more than 1 level deep:
[
{
"kind": "Listing",
"data": {
"modhash": "pdyhr8d2dgf5ffd0f279801a563bc45cdfd0fd52fb2caa3c86",
"children": [
{
"kind": "t3",
"data": {
"domain": "rankery.com",
"banned_by": null,
"media_embed": {
},
"subreddit": "test",
"selftext_html": null,
"selftext": "",
"likes": true,
"suggested_sort": null,
"user_reports": [
],
"secure_media": null,
"link_flair_text": null,
"id": "39tnux",
"from_kind": null,
"gilded": 0,
"archived": false,
"clicked": false,
"report_reasons": null,
"author": "rankery",
"media": null,
"name": "t3_39tnux",
"score": 2,
"approved_by": null,
"over_18": false,
"hidden": false,
"thumbnail": "default",
"subreddit_id": "t5_2qh23",
"edited": false,
"link_flair_css_class": null,
"author_flair_css_class": null,
"downs": 0,
"mod_reports": [
],
"secure_media_embed": {
},
"saved": false,
"removal_reason": null,
"from": null,
"is_self": false,
"from_id": null,
"permalink": "/r/test/comments/39tnux/rb_test/",
"stickied": false,
"created": 1434307698.0,
"url": "http://www.rankery.com/redditBot1.php",
"author_flair_text": null,
"title": "RB TEST",
"created_utc": 1434304098.0,
"ups": 2,
"upvote_ratio": 1.0,
"num_comments": 21,
"visited": false,
"num_reports": null,
"distinguished": null
}
}
],
"after": null,
"before": null
}
},
{
"kind": "Listing",
"data": {
"modhash": "pdyhr8d2dgf5ffd0f279801a563bc45cdfd0fd52fb2caa3c86",
"children": [
{
"kind": "t1",
"data": {
"subreddit_id": "t5_2qh23",
"banned_by": null,
"removal_reason": null,
"link_id": "t3_39tnux",
"likes": true,
"replies": {
"kind": "Listing",
"data": {
"modhash": "pdyhr8d2dgf5ffd0f279801a563bc45cdfd0fd52fb2caa3c86",
"children": [
{
"kind": "t1",
"data": {
"subreddit_id": "t5_2qh23",
"banned_by": null,
"removal_reason": null,
"link_id": "t3_39tnux",
"likes": true,
"replies": "",
"user_reports": [
],
"saved": false,
"id": "csrd4vg",
"gilded": 0,
"archived": false,
"report_reasons": null,
"author": "rankery",
"parent_id": "t1_cspyeux",
"score": 1,
"approved_by": null,
"controversiality": 0,
"body": "SEARCH STRING",
"edited": 1435959047.0,
"author_flair_css_class": null,
"downs": 0,
"body_html": "<div class=\"md\"><p><a href=\"http://www.rankery.com/incl/redditBot/addRanking.phpid=81\">TEST</a></p>\n</div>",
"subreddit": "test",
"score_hidden": false,
"name": "t1_csrd4vg",
"created": 1435986571.0,
"author_flair_text": null,
"created_utc": 1435957771.0,
"distinguished": null,
"mod_reports": [
],
"num_reports": null,
"ups": 1
}
}
],
"after": null,
"before": null
}
},
"user_reports": [
],
"saved": false,
"id": "cspyeux",
"gilded": 0,
"archived": false,
"report_reasons": null,
"author": "rankery",
"parent_id": "t1_csa56v2",
"score": 1,
"approved_by": null,
"controversiality": 0,
"body": "Random+String%3A+q6K1CmU5FnpW3JO0ij7d9RYPGeZwl24A",
"edited": false,
"author_flair_css_class": null,
"downs": 0,
"body_html": "<div class=\"md\"><p>Random+String%3A+q6K1CmU5FnpW3JO0ij7d9RYPGeZwl24A</p>\n</div>",
"subreddit": "test",
"score_hidden": false,
"name": "t1_cspyeux",
"created": 1435855800.0,
"author_flair_text": null,
"created_utc": 1435852200.0,
"distinguished": null,
"mod_reports": [
],
"num_reports": null,
"ups": 1
}
}
],
"after": null,
"before": null
}
}
]
EDIT: Added JSON Object Example
EDIT 2: ADDED 'SEARCH STRING' into the JSON object to match the example at the top
It looks like body is URL-encoded, so try:
if (strpos(urldecode($block->data->body),$id) !== false) {
I am workin in PHP/MYSql application. i am geting data in php like follow
[
{
"id": "4",
"rawId": "4",
"displayName": "123 456",
"name": {
"familyName": "456",
"formatted": "123 456",
"givenName": "123"
},
"nickname": null,
"phoneNumbers": null,
"emails": null,
"addresses": null,
"ims": [
{
"type": -1,
"value": ".adgjm",
"id": "8",
"pref": false
}
],
"organizations": null,
"birthday": null,
"note": null,
"photos": null,
"categories": null,
"urls": null
},
{
"id": "5",
"rawId": "5",
"displayName": "Dooney Evans",
"name": {
"middleName": "",
"familyName": "Evans",
"formatted": "Dooney Evans",
"givenName": "Dooney"
},
"nickname": null,
"phoneNumbers": [
{
"type": "work",
"value": "512-555-1234",
"id": "11",
"pref": false
}
],
"emails": null,
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": null,
"photos": null,
"categories": null,
"urls": null
},
{
"id": "18",
"rawId": "18",
"displayName": "John Doe",
"name": {
"familyName": "Doe",
"formatted": "John Doe",
"givenName": "John"
},
"nickname": null,
"phoneNumbers": null,
"emails": null,
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": null,
"photos": null,
"categories": null,
"urls": null
},
{
"id": "19",
"rawId": "19",
"displayName": "Rob Doe",
"name": {
"familyName": "Doe",
"formatted": "Rob Doe",
"givenName": "Rob"
},
"nickname": null,
"phoneNumbers": null,
"emails": null,
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": null,
"photos": null,
"categories": null,
"urls": null
}
]
Currently it has key in key have may value. may another array, may object and sometimes also array and object goes more nested.
For now i am doing this php to display properly
is there another good or proper way?
$data = json_decode($data);
if(is_array($data))
{
echo '<pre>';
for($i = 0; $i< count($data); $i++)
{
$record = $data[$i];
foreach($record as $key => $value)
{
if($value)
if(is_object($value))
{
foreach($value as $key1 => $value1)
{
echo $key1." = ".$value1."<br />";
}
}
else if (is_array($value))
{
for($j = 0; $j< count($value); $j++)
{
$innerValue = $value[$j];
if(is_object($innerValue))
{
foreach($innerValue as $key1 => $value1)
{
echo $key1." = ".$value1."<br />";
}
}
else if (is_array($innerValue))
{
}
else
{
echo $key." = ".$value."<br />";
}
}
}
else
{
echo $key." = ".$value."<br />";
}
}
//print_r($record);
}
}
You could try using a recursive function, instead of nesting that much:
Pass the function an Array, the output of json_decode($json) for example.
function print_json($json) {
if (is_array($json) || is_object($json)) {
echo "<table width=100%>";
$type = 'Array';
if(is_object($json)) $type = 'Object';
echo '<tr><td colspan=2 style="background-color:#333333;">
<strong><font color=white>'.$type.'</font></strong>
</td></tr>';
foreach ($json as $k => $v) {
echo '<tr><td valign="top" style="background-color:#F0F0F0;">';
echo '<strong>'.$k.'</strong></td><td>';
print_json($v);
echo "</td></tr>";
}
echo "</table>";
return;
}
echo $json;
}
Run in PHP Fiddle