Access Google Calender JSON using PHP - php

I'm tiring to get holidays from google api here is my php code. which return json data from google corretcly
$calendar_id = urlencode('japanese.ja#holiday.calendar.google.com');
// ε–εΎ—ζœŸι–“
$start = date("Y-01-01\T00:00:00\Z");
$end = date("Y-12-31\T00:00:00\Z");
$url = 'https://www.googleapis.com/calendar/v3/calendars/en.japanese%23holiday%40group.v.calendar.google.com/events?key=apikeyhere';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
if (!empty($result)) {
$json = json_decode($result);
foreach($json->items as $mydata)
{
foreach($mydata as $values)
{
echo $values->summary . "\n";
echo $values->start. "\n";
}
}
I need to get summery and start from that data but above code show nothing, i tired using various foreach but didn't works. can someone help me please to get summery and start from it, thank you
Here is the part output json from google calender v3
{
"kind": "calendar#events",
"etag": "\"p33sets73qumdi0g\"",
"summary": "Holidays in Japan",
"updated": "2018-02-16T08:53:55.000Z",
"timeZone": "UTC",
"accessRole": "reader",
"defaultReminders": [],
"nextSyncToken": "CMCd1N-HqtkCEAAYAQ==",
"items": [
{
"kind": "calendar#event",
"etag": "\"2778543254000000\"",
"id": "20170109_60o30d9l6go30e1g60o30dr564",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAxNzAxMDlfNjBvMzBkOWw2Z28zMGUxZzYwbzMwZHI1NjQgZW4uamFwYW5lc2UjaG9saWRheUB2",
"created": "2014-01-09T12:47:07.000Z",
"updated": "2014-01-09T12:47:07.000Z",
"summary": "Coming of Age Day",
"creator": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"organizer": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"start": {
"date": "2017-01-09"
},
"end": {
"date": "2017-01-10"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20170109_60o30d9l6go30e1g60o30dr564#google.com",
"sequence": 0
},
{
"kind": "calendar#event",
"etag": "\"2778543254000000\"",
"id": "20170717_60o30d9lcgo30e1g60o30dr564",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAxNzA3MTdfNjBvMzBkOWxjZ28zMGUxZzYwbzMwZHI1NjQgZW4uamFwYW5lc2UjaG9saWRheUB2",
"created": "2014-01-09T12:47:07.000Z",
"updated": "2014-01-09T12:47:07.000Z",
"summary": "Sea Day",
"creator": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"organizer": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"start": {
"date": "2017-07-17"
},
"end": {
"date": "2017-07-18"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20170717_60o30d9lcgo30e1g60o30dr564#google.com",
"sequence": 0
},
{
"kind": "calendar#event",
"etag": "\"2778543254000000\"",
"id": "20170918_60o30d9lcko32e1g60o30dr564",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAxNzA5MThfNjBvMzBkOWxja28zMmUxZzYwbzMwZHI1NjQgZW4uamFwYW5lc2UjaG9saWRheUB2",
"created": "2014-01-09T12:47:07.000Z",
"updated": "2014-01-09T12:47:07.000Z",
"summary": "Respect for the Aged Day",
"creator": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"organizer": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"start": {
"date": "2017-09-18"
},
"end": {
"date": "2017-09-19"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20170918_60o30d9lcko32e1g60o30dr564#google.com",
"sequence": 0
},
{
"kind": "calendar#event",
"etag": "\"2778543254000000\"",
"id": "20171009_60o30d9l6ko30e1g60o30dr564",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAxNzEwMDlfNjBvMzBkOWw2a28zMGUxZzYwbzMwZHI1NjQgZW4uamFwYW5lc2UjaG9saWRheUB2",
"created": "2014-01-09T12:47:07.000Z",
"updated": "2014-01-09T12:47:07.000Z",
"summary": "Sports Day",
"creator": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"organizer": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"start": {
"date": "2017-10-09"
},
"end": {
"date": "2017-10-10"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20171009_60o30d9l6ko30e1g60o30dr564#google.com",
"sequence": 0
}
]
}
**I converted this code from js code which have working json part
data variable is the json out put from google, i just need convert this part to php**
for (item in data.items) {
$("#output").append(
"<hr><h3>" + data.items[item].summary + "<h3>" +
"<h4>" + data.items[item].start.date + "<h4>"
);
}

Your code is almost correct, you just have one foreach loop too many, once you are iterating over the items you can access their properties directly, no need to loop through them.
// Check if we got some results
if (!empty($result)) {
// Parse the results
$json = json_decode($result);
// Iterate over the item property of the resultset
foreach($json->items as $item) {
// Each item is an object,
// 'summary' and 'start' are properties of 'item'
// 'date' is a property of 'start'
echo '<hr><h3>' . $item->summary . '</h3>';
echo '<h4>' . $item->start->date . '</h4>';
}
}
I changed the name of $myData to $item, I feel that it makes the code easier to understand, feel free to update the answer if you want to preserve the name $mydata.

Related

How to read Specific value from curl Response

this is my response
i need to read first line id value & url of sandbox
{
"id": "chg_g5Y25220190539Ob590811651",
"object": "charge",
"live_mode": false,
"api_version": "V2",
"method": "CREATE",
"status": "INITIATED",
"amount": 1.000,
"currency": "KWD",
"threeDSecure": false,
"card_threeDSecure": false,
"save_card": false,
"statement_descriptor": "Sample",
"description": "Test DESC",
"transaction":
{
"timezone": "UTC+03:00",
"created": "1573191592651",
"url": "https://sandbox.payments.tap.company/test_gosell/v2/payment/response.aspx?tap_chg=PsV8hZdr78kEIAOZl9XL1B5u3dXe%2bBQ%2b3Hrd%2fempxYs%3d&sess=noWi606EI%2bM%3d&token=PsV8hZdr78kEIAOZl9XL1B5u3dXe%2bBQ%2bTyYdQy9iGpS6aAXwKOqAdw%3d%3d",
"expiry": { "period": 30, "type": "MINUTE" },
"asynchronous": false
},
"reference": { "transaction": "txn_0001", "order": "ord_0001" },
"response": { "code": "100", "message": "Initiated" },
"receipt": { "email": true, "sms": true },
"customer": { "first_name": "yxy", "last_name": "ttt", "email": "xyx#xyz.com" },
"source": { "object": "source", "id": "src_card" },
"redirect": { "status": "PENDING", "url": "http://localhost:81/School/" },
"post": { "status": "PENDING", "url": "http://localhost:81/School/" } }
assuming you have your response from curl in a variable called $resp
$resp_decoded = json_decode($resp,TRUE);
print($resp_decoded['id']);
print($resp_decoded['transaction']['url']);

Access Values of JSON Multi Dimensional Array in PHP

I have attempted to parse the below ($var) using both
$convert = json_encode($var);
$object = (object)json_decode($convert);
$array = json_decode($convert, TRUE);
but appear to be unable to access values (typically seeing nothing/null), through something like $array->messages->event.
I've been cross referencing against some example code at https://gist.githubusercontent.com/eurica/6034108/raw/10e7fbce580e515db0f0b74d49c812da4e5ce40b/PagerDutyWebhookToEmail.php. However, it appears to be dated (v1 payload instead of v2).
My goal is to pull different values, at different levels, to create a custom email. Documentation suggests there could be multiple "message" under "messages" and therefore a foreach could be necessary?
X-REF https://community.pagerduty.com/t/how-do-i-notify-a-distribution-list-or-shared-group-email-address/1519 & https://v2.developer.pagerduty.com/docs/webhooks-v2-overview
{
"messages": [{
"event": "incident.trigger",
"log_entries": [
{
"id": "R2XGXEI3W0FHMSDXHDIBQGBQ5E",
"type": "trigger_log_entry",
"summary": "Triggered through the website",
"self": "https://api.pagerduty.com/log_entries/R2XGXEI3W0FHMSDXHDIBQGBQ5E",
"html_url": "https://webdemo.pagerduty.com/incidents/PRORDTY/log_entries/R2XGXEI3W0FHMSDXHDIBQGBQ5E",
"created_at": "2017-09-26T15:14:36Z",
"agent": {
"id": "P553OPV",
"type": "user_reference",
"summary": "Laura Haley",
"self": "https://api.pagerduty.com/users/P553OPV",
"html_url": "https://webdemo.pagerduty.com/users/P553OPV"
},
"channel": {
"type": "web_trigger",
"summary": "My new incident",
"subject": "My new incident",
"details": "Oh my gosh"
},
"service": {
"id": "PN49J75",
"type": "service_reference",
"summary": "Production XDB Cluster",
"self": "https://api.pagerduty.com/services/PN49J75",
"html_url": "https://webdemo.pagerduty.com/services/PN49J75"
},
"incident": {
"id": "PRORDTY",
"type": "incident_reference",
"summary": "[#33] My new incident",
"self": "https://api.pagerduty.com/incidents/PRORDTY",
"html_url": "https://webdemo.pagerduty.com/incidents/PRORDTY"
},
"teams": [
{
"id": "P4SI59S",
"type": "team_reference",
"summary": "Engineering",
"self": "https://api.pagerduty.com/teams/P4SI59S",
"html_url": "https://webdemo.pagerduty.com/teams/P4SI59S"
}
],
"contexts": [],
"event_details": {
"description": "My new incident"
}
}
],
"webhook": {
"endpoint_url": "https://requestb.in/18ao6fs1",
"name": "V2 wabhook",
"description": null,
"webhook_object": {
"id": "PN49J75",
"type": "service_reference",
"summary": "Production XDB Cluster",
"self": "https://api.pagerduty.com/services/PN49J75",
"html_url": "https://webdemo.pagerduty.com/services/PN49J75"
},
"config": {},
"outbound_integration": {
"id": "PJFWPEP",
"type": "outbound_integration_reference",
"summary": "Generic V2 Webhook",
"self": "https://api.pagerduty.com/outbound_integrations/PJFWPEP",
"html_url": null
},
"accounts_addon": null,
"id": "PKT9NNX",
"type": "webhook",
"summary": "V2 wabhook",
"self": "https://api.pagerduty.com/webhooks/PKT9NNX",
"html_url": null
},
"incident": {
"incident_number": 33,
"title": "My new incident",
"description": "My new incident",
"created_at": "2017-09-26T15:14:36Z",
"status": "triggered",
"pending_actions": [
{
"type": "escalate",
"at": "2017-09-26T15:44:36Z"
},
{
"type": "resolve",
"at": "2017-09-26T19:14:36Z"
}
],
"incident_key": "56a1c5594fe340408230783eebf43be6",
"service": {
"id": "PN49J75",
"name": "Production XDB Cluster",
"description": "This service was created during onboarding on July 5, 2017.",
"auto_resolve_timeout": 14400,
"acknowledgement_timeout": 1800,
"created_at": "2017-07-05T17:33:09Z",
"status": "critical",
"last_incident_timestamp": "2017-09-26T15:14:36Z",
"teams": [
{
"id": "P4SI59S",
"type": "team_reference",
"summary": "Engineering",
"self": "https://api.pagerduty.com/teams/P4SI59S",
"html_url": "https://webdemo.pagerduty.com/teams/P4SI59S"
}
],
"incident_urgency_rule": {
"type": "constant",
"urgency": "high"
},
"scheduled_actions": [],
"support_hours": null,
"escalation_policy": {
"id": "PINYWEF",
"type": "escalation_policy_reference",
"summary": "Default",
"self": "https://api.pagerduty.com/escalation_policies/PINYWEF",
"html_url": "https://webdemo.pagerduty.com/escalation_policies/PINYWEF"
},
"addons": [],
"privilege": null,
"alert_creation": "create_alerts_and_incidents",
"integrations": [
{
"id": "PUAYF96",
"type": "generic_events_api_inbound_integration_reference",
"summary": "API",
"self": "https://api.pagerduty.com/services/PN49J75/integrations/PUAYF96",
"html_url": "https://webdemo.pagerduty.com/services/PN49J75/integrations/PUAYF96"
},
{
"id": "P90GZUH",
"type": "generic_email_inbound_integration_reference",
"summary": "Email",
"self": "https://api.pagerduty.com/services/PN49J75/integrations/P90GZUH",
"html_url": "https://webdemo.pagerduty.com/services/PN49J75/integrations/P90GZUH"
}
],
"metadata": {},
"type": "service",
"summary": "Production XDB Cluster",
"self": "https://api.pagerduty.com/services/PN49J75",
"html_url": "https://webdemo.pagerduty.com/services/PN49J75"
},
"assignments": [
{
"at": "2017-09-26T15:14:36Z",
"assignee": {
"id": "P553OPV",
"type": "user_reference",
"summary": "Laura Haley",
"self": "https://api.pagerduty.com/users/P553OPV",
"html_url": "https://webdemo.pagerduty.com/users/P553OPV"
}
}
],
"acknowledgements": [],
"last_status_change_at": "2017-09-26T15:14:36Z",
"last_status_change_by": {
"id": "PN49J75",
"type": "service_reference",
"summary": "Production XDB Cluster",
"self": "https://api.pagerduty.com/services/PN49J75",
"html_url": "https://webdemo.pagerduty.com/services/PN49J75"
},
"first_trigger_log_entry": {
"id": "R2XGXEI3W0FHMSDXHDIBQGBQ5E",
"type": "trigger_log_entry_reference",
"summary": "Triggered through the website",
"self": "https://api.pagerduty.com/log_entries/R2XGXEI3W0FHMSDXHDIBQGBQ5E",
"html_url": "https://webdemo.pagerduty.com/incidents/PRORDTY/log_entries/R2XGXEI3W0FHMSDXHDIBQGBQ5E"
},
"escalation_policy": {
"id": "PINYWEF",
"type": "escalation_policy_reference",
"summary": "Default",
"self": "https://api.pagerduty.com/escalation_policies/PINYWEF",
"html_url": "https://webdemo.pagerduty.com/escalation_policies/PINYWEF"
},
"privilege": null,
"teams": [
{
"id": "P4SI59S",
"type": "team_reference",
"summary": "Engineering",
"self": "https://api.pagerduty.com/teams/P4SI59S",
"html_url": "https://webdemo.pagerduty.com/teams/P4SI59S"
}
],
"alert_counts": {
"all": 0,
"triggered": 0,
"resolved": 0
},
"impacted_services": [
{
"id": "PN49J75",
"type": "service_reference",
"summary": "Production XDB Cluster",
"self": "https://api.pagerduty.com/services/PN49J75",
"html_url": "https://webdemo.pagerduty.com/services/PN49J75"
}
],
"is_mergeable": true,
"basic_alert_grouping": null,
"alert_grouping": null,
"metadata": {},
"external_references": [],
"importance": null,
"incidents_responders": [],
"responder_requests": [],
"subscriber_requests": [],
"urgency": "high",
"id": "PRORDTY",
"type": "incident",
"summary": "[#33] My new incident",
"self": "https://api.pagerduty.com/incidents/PRORDTY",
"html_url": "https://webdemo.pagerduty.com/incidents/PRORDTY"
},
"id": "69a7ced0-a2cd-11e7-a799-22000a15839c",
"created_on": "2017-09-26T15:14:36Z"
}
]}
Answer Testing:
echo $object->messages[0]->event;
Notice: Undefined property: stdClass::$messages in
/var/www/pagerduty/public_html/wh/index.php on line 251
echo $array->messages[0]->event;
Notice: Trying to get property of non-object in
/var/www/pagerduty/public_html/wh/index.php on line 255
echo $array['messages'][0]['event']
Warning: Illegal string offset 'messages' in
/var/www/pagerduty/public_html/wh/index.php on line 258
Warning: Illegal string offset 'event' in
/var/www/pagerduty/public_html/wh/index.php on line 258
{
print_r($array);
{ "messages": [ { "event": "incident.trigger", "log_entries": [ { "id": "R2XGXEI3W0FHMSDXHDIBQGBQ5E", "type": "trigger_log_entry", "summary": "Triggered through the website", "self": "https://api.pagerduty.com/log_entries/R2XGXEI3W0FHMSDXHDIBQGBQ5E", "html_url": "https://webdemo.pagerduty.com/incidents/PRORDTY/log_entries/R2XGXEI3W0FHMSDXHDIBQGBQ5E", "created_at": "2017-09-26T15:14:36Z", "agent": { "id": "P553OPV", "type": "user_reference", "summary": "Laura Haley", "self": "https://api.pagerduty.com/users/P553OPV", "html_url": "https://webdemo.pagerduty.com/users/P553OPV" }, "channel": { "type": "web_trigger", "summary": "My new incident", "subject": "My new incident", "details": "Oh my gosh" }, "service": { "id": "PN49J75", "type": "service_reference", "summary": "Production XDB Cluster", "self": "https://api.pagerduty.com/services/PN49J75", "html_url": "https://webdemo.pagerduty.com/services/PN49J75" }, "incident": { "id": "PRORDTY", "type": "incident_reference", "summary": "[#33] My new incident", "self": "https://api.pagerduty.com/incidents/PRORDTY", "html_url": "https://webdemo.pagerduty.com/incidents/PRORDTY" }, "teams": [ { "id": "P4SI59S", "type": "team_reference", "summary": "Engineering", "self": "https://api.pagerduty.com/teams/P4SI59S", "html_url": "https://webdemo.pagerduty.com/teams/P4SI59S" } ], "contexts": [], "event_details": { "description": "My new incident" } } ], "webhook": { "endpoint_url": "https://requestb.in/18ao6fs1", "name": "V2 wabhook", "description": null, "webhook_object": { "id": "PN49J75", "type": "service_reference", "summary": "Production XDB Cluster", "self": "https://api.pagerduty.com/services/PN49J75", "html_url": "https://webdemo.pagerduty.com/services/PN49J75" }, "config": {}, "outbound_integration": { "id": "PJFWPEP", "type": "outbound_integration_reference", "summary": "Generic V2 Webhook", "self": "https://api.pagerduty.com/outbound_integrations/PJFWPEP", "html_url": null }, "accounts_addon": null, "id": "PKT9NNX", "type": "webhook", "summary": "V2 wabhook", "self": "https://api.pagerduty.com/webhooks/PKT9NNX", "html_url": null }, "incident": { "incident_number": 33, "title": "My new incident", "description": "My new incident", "created_at": "2017-09-26T15:14:36Z", "status": "triggered", "pending_actions": [ { "type": "escalate", "at": "2017-09-26T15:44:36Z" }, { "type": "resolve", "at": "2017-09-26T19:14:36Z" } ], "incident_key": "56a1c5594fe340408230783eebf43be6", "service": { "id": "PN49J75", "name": "Production XDB Cluster", "description": "This service was created during onboarding on July 5, 2017.", "auto_resolve_timeout": 14400, "acknowledgement_timeout": 1800, "created_at": "2017-07-05T17:33:09Z", "status": "critical", "last_incident_timestamp": "2017-09-26T15:14:36Z", "teams": [ { "id": "P4SI59S", "type": "team_reference", "summary": "Engineering", "self": "https://api.pagerduty.com/teams/P4SI59S", "html_url": "https://webdemo.pagerduty.com/teams/P4SI59S" } ], "incident_urgency_rule": { "type": "constant", "urgency": "high" }, "scheduled_actions": [], "support_hours": null, "escalation_policy": { "id": "PINYWEF", "type": "escalation_policy_reference", "summary": "Default", "self": "https://api.pagerduty.com/escalation_policies/PINYWEF", "html_url": "https://webdemo.pagerduty.com/escalation_policies/PINYWEF" }, "addons": [], "privilege": null, "alert_creation": "create_alerts_and_incidents", "integrations": [ { "id": "PUAYF96", "type": "generic_events_api_inbound_integration_reference", "summary": "API", "self": "https://api.pagerduty.com/services/PN49J75/integrations/PUAYF96", "html_url": "https://webdemo.pagerduty.com/services/PN49J75/integrations/PUAYF96" }, { "id": "P90GZUH", "type": "generic_email_inbound_integration_reference", "summary": "Email", "self": "https://api.pagerduty.com/services/PN49J75/integrations/P90GZUH", "html_url": "https://webdemo.pagerduty.com/services/PN49J75/integrations/P90GZUH" } ], "metadata": {}, "type": "service", "summary": "Production XDB Cluster", "self": "https://api.pagerduty.com/services/PN49J75", "html_url": "https://webdemo.pagerduty.com/services/PN49J75" }, "assignments": [ { "at": "2017-09-26T15:14:36Z", "assignee": { "id": "P553OPV", "type": "user_reference", "summary": "Laura Haley", "self": "https://api.pagerduty.com/users/P553OPV", "html_url": "https://webdemo.pagerduty.com/users/P553OPV" } } ], "acknowledgements": [], "last_status_change_at": "2017-09-26T15:14:36Z", "last_status_change_by": { "id": "PN49J75", "type": "service_reference", "summary": "Production XDB Cluster", "self": "https://api.pagerduty.com/services/PN49J75", "html_url": "https://webdemo.pagerduty.com/services/PN49J75" }, "first_trigger_log_entry": { "id": "R2XGXEI3W0FHMSDXHDIBQGBQ5E", "type": "trigger_log_entry_reference", "summary": "Triggered through the website", "self": "https://api.pagerduty.com/log_entries/R2XGXEI3W0FHMSDXHDIBQGBQ5E", "html_url": "https://webdemo.pagerduty.com/incidents/PRORDTY/log_entries/R2XGXEI3W0FHMSDXHDIBQGBQ5E" }, "escalation_policy": { "id": "PINYWEF", "type": "escalation_policy_reference", "summary": "Default", "self": "https://api.pagerduty.com/escalation_policies/PINYWEF", "html_url": "https://webdemo.pagerduty.com/escalation_policies/PINYWEF" }, "privilege": null, "teams": [ { "id": "P4SI59S", "type": "team_reference", "summary": "Engineering", "self": "https://api.pagerduty.com/teams/P4SI59S", "html_url": "https://webdemo.pagerduty.com/teams/P4SI59S" } ], "alert_counts": { "all": 0, "triggered": 0, "resolved": 0 }, "impacted_services": [ { "id": "PN49J75", "type": "service_reference", "summary": "Production XDB Cluster", "self": "https://api.pagerduty.com/services/PN49J75", "html_url": "https://webdemo.pagerduty.com/services/PN49J75" } ], "is_mergeable": true, "basic_alert_grouping": null, "alert_grouping": null, "metadata": {}, "external_references": [], "importance": null, "incidents_responders": [], "responder_requests": [], "subscriber_requests": [], "urgency": "high", "id": "PRORDTY", "type": "incident", "summary": "[#33] My new incident", "self": "https://api.pagerduty.com/incidents/PRORDTY", "html_url": "https://webdemo.pagerduty.com/incidents/PRORDTY" }, "id": "69a7ced0-a2cd-11e7-a799-22000a15839c", "created_on": "2017-09-26T15:14:36Z" } ] }
but appear to be unable to access values (typically seeing nothing/null), through something like $array->messages->event.
You can't access $array (that you received through json_decode($convert, true) like that.
Try accessing them like $array['messages'][0]['event']

PHP Getting a value from a Multi Layered JSON Array

I seem to be having some trouble with JSON arrays. I was wondering if someone could please assist me.
I have the following JSON Array, and I want to get the figure in invoice_number
$json = '
{
"id": "PAY-7MP775806F4135612LLCHE4I",
"intent": "sale",
"state": "approved",
"cart": "9KA22662P3559221J",
"payer":
{
"payment_method": "paypal",
"status": "VERIFIED",
"payer_info":
{
"email": "accounts-buyer#traxprint.com",
"first_name": "test",
"last_name": "buyer",
"payer_id": "ZR6SRXGS252RG",
"shipping_address":
{
"recipient_name": "test buyer",
"line1": "1 Cheeseman Ave Brighton East",
"city": "Melbourne",
"state": "Victoria",
"postal_code": "3001",
"country_code": "AU"
},
"phone": "0364424947",
"country_code": "AU"
}
},
"transactions":
[
{
"amount":
{
"total": "3.00",
"currency": "USD",
"details":
{
"subtotal": "3.00"
}
},
"payee":
{
"merchant_id": "DSTEYCMCDUL3Y"
},
"description": "Payment description",
"invoice_number": "abc1231522823790",
"item_list":
{
"items":
[
{
"name": "Subscribe",
"sku": "sub1",
"price": "3.00",
"currency": "USD",
"tax": "0.00",
"quantity": 1
}
],
"shipping_address":
{
"recipient_name": "test buyer",
"line1": "1 Cheeseman Ave Brighton East",
"city": "Melbourne",
"state": "Victoria",
"postal_code": "3001",
"country_code": "AU"
}
},
"related_resources":
[
{
"sale":
{
"id": "41B66647LJ233225Y",
"state": "completed",
"amount":
{
"total": "3.00",
"currency": "USD",
"details":
{
"subtotal": "3.00"
}
},
"payment_mode": "INSTANT_TRANSFER",
"protection_eligibility": "ELIGIBLE",
"protection_eligibility_type": "ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE",
"transaction_fee":
{
"value": "0.37",
"currency": "USD"
},
"parent_payment": "PAY-7MP775806F4135612LLCHE4I",
"create_time": "2018-04-04T06:36:59Z",
"update_time": "2018-04-04T06:36:59Z",
"links":
[
{
"href": "https://api.sandbox.paypal.com/v1/payments/sale/41B66647LJ233225Y",
"rel": "self",
"method": "GET"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/sale/41B66647LJ233225Y/refund",
"rel": "refund",
"method": "POST"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-7MP775806F4135612LLCHE4I",
"rel": "parent_payment",
"method": "GET"
}
]
}
}
]
}
],
"create_time": "2018-04-04T06:36:33Z",
"links":
[
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-7MP775806F4135612LLCHE4I",
"rel": "self",
"method": "GET"
}
]
}';
The code I was trying to use is but it comes up with error Undefined property: stdClass::$invoice_number
$decoded = json_decode($json);
echo $Info = $decoded->transactions[0]->payee->invoice_number;
Could someone please tell me why this does not work?
Thanks
Robert
echo $Info = $decoded->transactions[0]->invoice_number;

json calling other json using php

I need your help..I would like to call a json value using a json value...
here's my sample json...
first json:
{
"first_name": "Richard Catibog",
"last_name": "",
"display_name": "Richard Catibog ",
"roles": {
"owner": false,
"administrator": true
},
"login_count": 108,
"enabled": true,
"departments": [
1817719575,
1817719887,
1817722991
],
"id": 4142095,
"last_login": "2017-07-12T10:03:57Z",
"create_date": "2017-04-28T12:09:57Z",
"email": "richard.catibog+21757948948#51talk.com"
},
{
"first_name": "Rovi Cruz",
"last_name": "",
"display_name": "Rovi Roy Cruz ",
"roles": {
"owner": false,
"administrator": true
},
"login_count": 98,
"enabled": true,
"departments": [
1817719575,
1817719887,
1817722991
],
"id": 4225009,
"last_login": "2017-07-13T00:37:27Z",
"create_date": "2017-06-05T06:15:49Z",
"email": "rovi.cruz+21821290968#51talk.com"
}
Second json:
[
{
"description": "Fees Support for American Academy",
"settings": {
},
"enabled": false,
"id": 1817719575,
"name": "AA Fees Support [L2]"
},
{
"description": "American Academy",
"settings": {
},
"enabled": true,
"id": 1817722991,
"name": "Lesson and Fee Support"
},
{
"description": "Technical Support",
"settings": {
},
"enabled": true,
"id": 1817719887,
"name": "Technical Support"
}
]
I would like to call the id on the second and echo the names using the departments id list on first json...
here's what i get...
but the result that i want to see is AA Fees Support [L2], Lesson and Fee Support and Technical Support...
thank you, hope you can help me...
In this I made an array $desc that is keyed on the departments id numbers so you can easily convert the id to a Descrition
$js1 = '{
"first_name": "Richard Catibog", "last_name": "",
"display_name": "Richard Catibog ",
"roles": { "owner": false,"administrator": true},
"login_count": 108,"enabled": true,
"departments": [1817719575,1817719887,1817722991],
"id": 4142095,"last_login": "2017-07-12T10:03:57Z",
"create_date": "2017-04-28T12:09:57Z",
"email": "richard.catibog+21757948948#51talk.com"
}';
$js2 = '[
{
"description": "Fees Support for American Academy",
"settings": {},"enabled": false,"id": 1817719575,
"name": "AA Fees Support [L2]"
},
{
"description": "American Academy",
"settings": {},"enabled": true,"id": 1817722991,
"name": "Lesson and Fee Support"
},
{
"description": "Technical Support",
"settings": {},"enabled": true,"id": 1817719887,
"name": "Technical Support"
}
]';
$first = json_decode($js1);
//print_r($first);
$second = json_decode($js2);
//print_r($second);
// make array key'd on the id
$desc = [];
foreach ($second as $s) {
$desc[$s->id] = $s;
}
print_r($desc);
// go through all the dept id's in the first array
// getting a matching desctipyion from array 2
foreach ( $first->departments as $dept) {
echo $desc[$dept]->description . PHP_EOL;
}
UPDATE: After the first json data structure got changed to an array of objects
NOTE I changed your first json data structure to make it valid JSON by adding [] around the 2 objects to make a valid JSON data structure i.e. an array of objects.
All you need to do in this case is add a loop to lop over the now array of objects.
$js1 = '[{
"first_name": "Richard Catibog",
"last_name": "",
"display_name": "Richard Catibog ",
"roles": { "owner": false, "administrator": true },
"login_count": 108,
"enabled": true,
"departments": [ 1817719575, 1817719887, 1817722991 ],
"id": 4142095,
"last_login": "2017-07-12T10:03:57Z",
"create_date": "2017-04-28T12:09:57Z",
"email": "richard.catibog+21757948948#51talk.com"
},
{
"first_name": "Rovi Cruz",
"last_name": "",
"display_name": "Rovi Roy Cruz ",
"roles": { "owner": false, "administrator": true },
"login_count": 98,
"enabled": true,
"departments": [ 1817719575, 1817719887, 1817722991 ],
"id": 4225009,
"last_login": "2017-07-13T00:37:27Z",
"create_date": "2017-06-05T06:15:49Z",
"email": "rovi.cruz+21821290968#51talk.com"
}]';
$js2 = '[
{
"description": "Fees Support for American Academy",
"settings": {},"enabled": false,"id": 1817719575,
"name": "AA Fees Support [L2]"
},
{
"description": "American Academy",
"settings": {},"enabled": true,"id": 1817722991,
"name": "Lesson and Fee Support"
},
{
"description": "Technical Support",
"settings": {},"enabled": true,"id": 1817719887,
"name": "Technical Support"
}
]';
$first = json_decode($js1);
//print_r($first);
$second = json_decode($js2);
//print_r($second);
// make array key'd on the id
$desc = [];
foreach ($second as $s) {
$desc[$s->id] = $s;
}
//print_r($desc);
//Loop through all the first array of object
foreach ( $first as $f) {
// go through all the dept id's in the first array
// getting a matching desctipyion from array 2
foreach ( $f->departments as $dept) {
echo $desc[$dept]->description . PHP_EOL;
}
echo PHP_EOL;
}
RESULT
Fees Support for American Academy
Technical Support
American Academy
Fees Support for American Academy
Technical Support
American Academy
here you go
$json1 = '{
"first_name": "Richard Catibog",
"last_name": "",
"display_name": "Richard Catibog ",
"roles": {
"owner": false,
"administrator": true
},
"login_count": 108,
"enabled": true,
"departments": [
1817719575,
1817719887,
1817722991
],
"id": 4142095,
"last_login": "2017-07-12T10:03:57Z",
"create_date": "2017-04-28T12:09:57Z",
"email": "richard.catibog+21757948948#51talk.com"
}
';
$json2 ='[
{
"description": "Fees Support for American Academy",
"settings": {
},
"enabled": false,
"id": 1817719575,
"name": "AA Fees Support [L2]"
},
{
"description": "American Academy",
"settings": {
},
"enabled": true,
"id": 1817722991,
"name": "Lesson and Fee Support"
},
{
"description": "Technical Support",
"settings": {
},
"enabled": true,
"id": 1817719887,
"name": "Technical Support"
}
]';
$json1 = json_decode($json1, true);
$json2 = json_decode($json2, true);
$department = function($id) use($json2) {
foreach($json2 as $dep) {
if($dep["id"] == $id) {
return $dep;
}
}
return false;
};
foreach($json1["departments"] as $id) {
$dep = $department($id);
if(is_array($dep)) {
echo sprintf("id: %s, name: %s\n", $id, $dep["name"]);
}
}

Parsing Rome2Rio json file with PHP

I am trying to extract a segment from the json file of Rome2Rio API with PHP but I cant get an output.
The json file from rome2rio:
{
"serveTime": 1,
"places": [
{ "kind": "town", "name": "Kozani", "longName": "Kozani, Greece", "pos": "40.29892,21.7972", "countryCode": "GR", "regionCode": "ESYE13" },
{ "kind": "city", "name": "Thessaloniki", "longName": "Thessaloniki, Greece", "pos": "40.64032,22.93527", "countryCode": "GR", "regionCode": "ESYE12" }
],
"airports": [],
"airlines": [],
"aircrafts": [],
"agencies": [{
"code": "KTEL",
"name": "KTEL",
"url": "http://www.ktelbus.com/?module=default\u0026pages_id=15\u0026lang=en",
"iconPath": "/logos/Trains/KTELgr.png",
"iconSize": "27,23",
"iconOffset": "0,0"
}
],
"routes": [
{ "name": "Bus", "distance": 121.04, "duration": 120, "totalTransferDuration": 0, "indicativePrice": { "price": 9, "currency": "EUR", "isFreeTransfer": 0 },
"stops": [
{ "name": "Kozani", "pos": "40.30032,21.79763", "kind": "station", "countryCode": "GR", "timeZone": "Europe/Athens" },
{ "name": "Thessaloniki", "pos": "40.6545,22.90233", "kind": "station", "countryCode": "GR", "timeZone": "Europe/Athens" }
]
The PHP code I wrote is:
$json_rome2rio = file_get_contents("http://free.rome2rio.com/api/1.2/json/Search?key=&oName=kozani&dName=thessaloniki");
$parsed_json_r = json_decode($json_rome2rio);
echo $parsed_json_r->agencies->name;
The agencies property contains an array of agencies (note the square brackets). To access the name as you're after, you can do the following:
echo $parsed_json_r->agencies[0]->name;
This assumes that at least one agency is returned and that the agency you are after is the first one if more than one is returned.

Categories