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) {
Related
I have two separate JSON arrays. Array 1 is called matches, Array 2 is called participants. Participants can be in many matches. I need some direction in how to look up the player id from matches within the matches array and return the corresponding participants name from the participants array.
Matches contains: player1_id and player2_d for each match.
Participants contains id for each player.
player1_id and player2_id will equal an id within the participants array, unless player1_id or player2_id is null.
Sample Match array:
[
{
"match": {
"attachment_count": null,
"created_at": "2015-01-19T16:57:17-05:00",
"group_id": null,
"has_attachment": false,
"id": 23575258,
"identifier": "A",
"location": null,
"loser_id": null,
"player1_id": 16543993,
"player1_is_prereq_match_loser": false,
"player1_prereq_match_id": null,
"player1_votes": null,
"player2_id": 16543997,
"player2_is_prereq_match_loser": false,
"player2_prereq_match_id": null,
"player2_votes": null,
"round": 1,
"scheduled_time": null,
"started_at": "2015-01-19T16:57:17-05:00",
"state": "open",
"tournament_id": 1086875,
"underway_at": null,
"updated_at": "2015-01-19T16:57:17-05:00",
"winner_id": null,
"prerequisite_match_ids_csv": "",
"scores_csv": ""
}
},
{
"match": {
"attachment_count": null,
"created_at": "2015-01-19T16:57:17-05:00",
"group_id": null,
"has_attachment": false,
"id": 23575259,
"identifier": "B",
"location": null,
"loser_id": null,
"player1_id": 16543994,
"player1_is_prereq_match_loser": false,
"player1_prereq_match_id": null,
"player1_votes": null,
"player2_id": 16543996,
"player2_is_prereq_match_loser": false,
"player2_prereq_match_id": null,
"player2_votes": null,
"round": 1,
"scheduled_time": null,
"started_at": "2015-01-19T16:57:17-05:00",
"state": "open",
"tournament_id": 1086875,
"underway_at": null,
"updated_at": "2015-01-19T16:57:17-05:00",
"winner_id": null,
"prerequisite_match_ids_csv": "",
"scores_csv": ""
}
},
{
"match": {
"attachment_count": null,
"created_at": "2015-01-19T16:57:17-05:00",
"group_id": null,
"has_attachment": false,
"id": 23575260,
"identifier": "C",
"location": null,
"loser_id": null,
"player1_id": null,
"player1_is_prereq_match_loser": false,
"player1_prereq_match_id": 23575258,
"player1_votes": null,
"player2_id": null,
"player2_is_prereq_match_loser": false,
"player2_prereq_match_id": 23575259,
"player2_votes": null,
"round": 2,
"scheduled_time": null,
"started_at": null,
"state": "pending",
"tournament_id": 1086875,
"underway_at": null,
"updated_at": "2015-01-19T16:57:17-05:00",
"winner_id": null,
"prerequisite_match_ids_csv": "23575258,23575259",
"scores_csv": ""
}
}
]
My sample participants array:
[
{
"participant": {
"active": true,
"checked_in_at": null,
"created_at": "2015-01-19T16:54:40-05:00",
"final_rank": null,
"group_id": null,
"icon": null,
"id": 16543993,
"invitation_id": null,
"invite_email": null,
"misc": null,
"name": "Participant #1",
"on_waiting_list": false,
"seed": 1,
"tournament_id": 1086875,
"updated_at": "2015-01-19T16:54:40-05:00",
"challonge_username": null,
"challonge_email_address_verified": null,
"removable": true,
"participatable_or_invitation_attached": false,
"confirm_remove": true,
"invitation_pending": false,
"display_name_with_invitation_email_address": "Participant #1",
"email_hash": null,
"username": null,
"attached_participatable_portrait_url": null,
"can_check_in": false,
"checked_in": false,
"reactivatable": false
}
},
{
"participant": {
"active": true,
"checked_in_at": null,
"created_at": "2015-01-19T16:54:43-05:00",
"final_rank": null,
"group_id": null,
"icon": null,
"id": 16543994,
"invitation_id": null,
"invite_email": null,
"misc": null,
"name": "Participant #2",
"on_waiting_list": false,
"seed": 2,
"tournament_id": 1086875,
"updated_at": "2015-01-19T16:54:43-05:00",
"challonge_username": null,
"challonge_email_address_verified": null,
"removable": true,
"participatable_or_invitation_attached": false,
"confirm_remove": true,
"invitation_pending": false,
"display_name_with_invitation_email_address": "Participant #2",
"email_hash": null,
"username": null,
"attached_participatable_portrait_url": null,
"can_check_in": false,
"checked_in": false,
"reactivatable": false
}
},
{
"participant": {
"active": true,
"checked_in_at": null,
"created_at": "2015-01-19T16:57:10-05:00",
"final_rank": null,
"group_id": null,
"icon": null,
"id": 16543996,
"invitation_id": null,
"invite_email": null,
"misc": null,
"name": "Participant #3",
"on_waiting_list": false,
"seed": 3,
"tournament_id": 1086875,
"updated_at": "2015-01-19T16:57:10-05:00",
"challonge_username": null,
"challonge_email_address_verified": null,
"removable": true,
"participatable_or_invitation_attached": false,
"confirm_remove": true,
"invitation_pending": false,
"display_name_with_invitation_email_address": "Participant #3",
"email_hash": null,
"username": null,
"attached_participatable_portrait_url": null,
"can_check_in": false,
"checked_in": false,
"reactivatable": false
}
},
{
"participant": {
"active": true,
"checked_in_at": null,
"created_at": "2015-01-19T16:57:12-05:00",
"final_rank": null,
"group_id": null,
"icon": null,
"id": 16543997,
"invitation_id": null,
"invite_email": null,
"misc": null,
"name": "Participant #4",
"on_waiting_list": false,
"seed": 4,
"tournament_id": 1086875,
"updated_at": "2015-01-19T16:57:12-05:00",
"challonge_username": null,
"challonge_email_address_verified": null,
"removable": true,
"participatable_or_invitation_attached": false,
"confirm_remove": true,
"invitation_pending": false,
"display_name_with_invitation_email_address": "Participant #4",
"email_hash": null,
"username": null,
"attached_participatable_portrait_url": null,
"can_check_in": false,
"checked_in": false,
"reactivatable": false
}
}
]
My desired output would be:
Participant #4 vs Participant #2
Participant #1 vs Participant #3
and so on for every match in the match array.
and so on.
To my knowledge, merging both arrays won't work because of the one to many relationship, but I could just be uneducated on merging. Any guidance on where to start would be appreiciated. I've looked at filtering too, but that doesn't seem to be my answer either.
This first indexes the participants by the id, it stores the whole array in case you need any other details later. The end result is an array called $participants indexed by the id.
Then it loops through the matches and extracts the two id's, if they both have a value, then it outputs the name from the stored array, otherwise uses Unknown for the name.
$participant = json_decode(file_get_contents("t.json"), true);
// Extract subarrays
$participants = array_column($participant, "participant");
// index by id
$participants = array_column($participants, null, "id");
$matches = json_decode(file_get_contents("a.json"), true);
foreach ( $matches as $match ) {
// Extract player ID's
$id1 = $match['match']['player1_id'];
$id2 = $match['match']['player2_id'];
if ( $id1 && $id2 ) {
echo $participants[$id1]["name"] . " vs " . $participants[$id2]["name"].PHP_EOL;
}
else {
echo "Unknown vs Unknown".PHP_EOL;
}
}
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");
What is the hierarchy here?
It looks like it goes
$event->data->object->lines->data->subscription
I've tried that though, and Im not getting an ID. It's actually pretty confusing.
Here is the response, and why I am assuming the hierarchy is
$event->data->object->lines->data->subscription
I figured if I used say
$subID = $event->data->object->lines->data->subscription;
then
$subID should = "sub_randcomSUB"
{
"object": {
"id": "in_randomnumbers",
"object": "invoice",
"amount_due": 20000,
"amount_paid": 0,
"amount_remaining": 20000,
"application_fee": null,
"attempt_count": 1,
"attempted": true,
"auto_advance": true,
"billing": "charge_automatically",
"billing_reason": "manual",
"charge": "ch_randomnumbers",
"closed": false,
"currency": "usd",
"customer": "cus_randomnumbers",
"date": 1532039357,
"description": null,
"discount": null,
"due_date": null,
"ending_balance": 0,
"forgiven": false,
"hosted_invoice_url": "https://pay.stripe.com/invoice/invst_randomnumbers",
"invoice_pdf": "https://pay.stripe.com/invoice/invst_randomcnumbers/pdf",
"lines": {
"object": "list",
"data": [
{
"id": "ii_randomnumbn",
"object": "line_item",
"amount": 20000,
"currency": "usd",
"description": "SSS",
"discountable": true,
"invoice_item": "ii_random",
"livemode": false,
"metadata": {
},
"period": {
"end": 1532039351,
"start": 1532039351
},
"plan": null,
"proration": false,
"quantity": 1,
"subscription": "sub_randcomSUB",
"type": "invoiceitem"
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/invoices/in_randcom/lines"
},
"livemode": false,
"metadata": {
},
"next_payment_attempt": 1532298568,
"number": "5186095-0004",
"paid": false,
"period_end": 1534715394,
"period_start": 1532036994,
"receipt_number": null,
"starting_balance": 0,
"statement_descriptor": null,
"subscription": null,
"subtotal": 20000,
"tax": null,
"tax_percent": null,
"total": 20000,
"webhooks_delivered_at": 1532039363
},
"previous_attributes": null
}
$event->data->object->lines->data is an array. You need to get the first element of the array like $event->data->object->lines->data[0] then subscription like $event->data->object->lines->data[0]->subscription
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 have really have troubles trying to work out why this is not working, and it seems like it should be easy, but just cannot seem to get it.
All I am looking to do is grab the sku field (which is VBP-01 below).
{
"variants": [
{
"id": 2314578,
"created_at": "2014-07-29T07:22:18.921Z",
"updated_at": "2015-05-21T15:42:42.136Z",
"product_id": 1188647,
"default_ledger_account_id": null,
"buy_price": "124.0",
"committed_stock": "0",
"incoming_stock": "3",
"composite": false,
"description": null,
"is_online": false,
"keep_selling": false,
"last_cost_price": "124.0",
"manage_stock": true,
"max_online": null,
"moving_average_cost": "124",
"name": "Lanparte battery pinch VBP-01",
"online_ordering": false,
"opt1": null,
"opt2": null,
"opt3": null,
"position": 1,
"product_name": "Lanparte V-Mount Battery Pinch",
"product_status": "active",
"product_type": null,
"retail_price": "0.0",
"sellable": true,
"sku": "VBP-01",
"status": "active",
"stock_on_hand": "1",
"supplier_code": "VBP-01",
"taxable": true,
"upc": null,
"weight": null,
"wholesale_price": "0.0",
"image_ids": [],
"variant_prices": [
{
"price_list_id": "buy",
"value": "124.0"
},
{
"price_list_id": "retail",
"value": "0.0"
},
{
"price_list_id": "wholesale",
"value": "0.0"
}
],
"locations": [
{
"location_id": 16377,
"stock_on_hand": "1",
"committed": null,
"incoming": "3",
"bin_location": null,
"reorder_point": 3
}
],
"prices": {
"buy": "124.0",
"retail": "0.0",
"wholesale": "0.0"
},
"stock_levels": {
"16377": "1.0"
},
"committed_stock_levels": {},
"incoming_stock_levels": {
"16377": "3.0"
}
}
],
"meta": {
"total": 1
}
}
Currently I using the following code with no luck
$url = "https://api.tradegecko.com/variants?sku=VBP-01";
$data = file_get_contents($url, false, $context);
$json = json_decode($data);
print $json->{'variant'}->{'sku'};
What I am doing wrong?
Just
echo $json->{'variants'}[0]->{'sku'};
In a loop
foreach ($json->variants as $variants) {
echo $variants->sku;
}