How to read multi layer php object - php

I get the following data from a webhook:
{
"id": 1,
"date_created": "2017-08-31T11:26:38.000Z",
"date_approved": "2017-08-31T11:26:38.000Z",
"date_last_updated": "2017-08-31T11:26:38.000Z",
"money_release_date": "2017-09-14T11:26:38.000Z",
"payment_method_id": "account_money",
"payment_type_id": "credit_card",
"status": "approved",
"status_detail": "accredited",
"currency_id": "BRL",
"description": "Pago Pizza",
"collector_id": 2,
"payer": {
"id": 123,
"email": "afriend#gmail.com",
"identification": {
"type": "DNI",
"number": 12345678
},
"type": "customer"
},
"metadata": {},
"additional_info": {},
"transaction_amount": 250,
"transaction_amount_refunded": 0,
"coupon_amount": 0,
"transaction_details": {
"net_received_amount": 250,
"total_paid_amount": 250,
"overpaid_amount": 0,
"installment_amount": 250
},
"installments": 1,
"card": {}
}
I get this data from the following expression:
$payment = null;
$payment = MercadoPago\Payment::find_by_id($_GET["data_id"]);
And I access the data as below:
$pStatus = $payment->status;
$payID = $payment->id;
But I still did not figure out how to access the nested values as for instance, the email.
I tried to convert the object to an array as in:
$responseArray = $payment->toArray();
So I could access the email using:
$responseArray['payer']['email']
But not working...
I need to read all nested values.
Assistance welcome.

Related

How can I encode an array into json with additional data?

I am creating a json file from my array:
$file = json_encode($array);
The json file will look like this:
[
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
But I need to create a json file with some little bit different format. The output I need is:
{
"draw": 1,
"recordsTotal": 5000,
"recordsFiltered": 5000,
"data": [
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
}
Is this possible with json_encode?
Create a new array with rest of the info and assign current array data into it as well.
$newArray = array(
'draw'=> 1,
'recordsTotal'=> 5000,
'recordsFiltered'=> 5000,
'data'=>$array
);
$file = json_encode($newArray);

Delete unwanted data from api result

I have a project in laravel which has API. I'm asking the API for posts(I call them recommendation).
Now my api response look like this -
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
...
...
...
All is good but I don't wanna likes_count to be in the result. It is a relation method. I get from it all I need. It is if the user liked this post. And it is is_liked in the result . but likes_count automatically added to the response .
if($item->likesCount->contains($user->id)){
$item['is_liked']='true';
}
I tried delete it with
foreach ($recommendations as $item) {
unset($item['likes_count']);
}
But it doesn't do it.
I think the problem is how you are referencing the object data structure. You are attempting to unset() something that doesn't exist so no error is thrown but the likes_count isn't getting removed either.
Here's your code example (fixed and modified for demonstration):
<?php
$apiResult = <<<eod
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
},
{
"id": 4,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
]
}
}
eod;
$result = json_decode($apiResult);
$data = $result->data->data;
var_dump($data);
// This should remove the likes_count array from the $result structure.
foreach ($data as &$item) {
unset($item->likes_count);
}
var_dump($data);
A quick way would be to make that 'attribute' (relation) hidden:
$recommendations->makeHidden('likes_count');
Though I am not sure how you are building your response.

PHP - Retrieve JSON data and values [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm new into PHP and JSON and I have a problem, I want to retrieve a item and value from a JSON:
{
"status": true,
"webhook_type": 100,
"data": {
"product": {
"id": "lSEADIQ",
"attachment_id": null,
"title": "Registration",
"description": null,
"image": null,
"unlisted": false,
"type": "service",
"price": 1,
"currency": "EUR",
"email": {
"enabled": false
},
"stock_warning": 0,
"quantity": {
"min": 1,
"max": 1
},
"confirmations": 1,
"custom_fields": [
{
"name": "Forum username",
"type": "text",
"required": true
}
],
"gateways": [
"Bitcoin"
],
"webhook_urls": [],
"dynamic_url": "",
"position": null,
"created_at": "2018-10-01 12:51:12",
"updated_at": "2018-10-01 12:55:46",
"stock": 9223372036854776000,
"accounts": []
},
"order": {
"id": "8e23b496-121a-4dc6-8ec4-c45835680db2",
"created_at": "Tue, 02 Oct 2018 00:54:56 +0200",
"paid_at": null,
"transaction_id": null,
"confirmations": 1,
"required_confirmations": 3,
"received_amount": 0,
"crypto_address": "1NeNQws7JLbTr6bjekfeaXSV7XiyRsv7V8",
"crypto_amount": "0.4815",
"quantity": 1,
"price": 19.99,
"currency": "EUR",
"exchange_rate": "1.21",
"gateway": "BTC",
"email": "webhook#site.gg",
"ip_address": "123.456.789.111",
"agent": {
"geo": {
"ip": "214.44.18.6",
"iso_code": "US",
"country": "United States"
},
"data": {
"is_mobile": false,
"is_table": false,
"is_desktop": true,
"browser": {
"name": "Chrome",
"version": "63.0.3239.132"
}
}
},
"custom_fields": [
{
"name": "user_id",
"value": 184191
}
],
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)"
}
}
}
I want to retrieve items from data -> order, for example "id" or "ip_address".
Thank you for read this, I hope someone can help me in this, because I'm lost, I started to code very recently and I'm trying to learn a lot.
Regards!
Where test.json is the json you uploaded, place it in a file named test.json and ensure its placed in the same directory.
<?php
$load = file_get_contents("test.json") or die("JSON load failed");
$json_a = json_decode($load, true);
print $json_a['data']['order']['ip_address'] . "\n";
?>
Gives:
123.456.789.111
My answer reads the JSON from a file as were it dumped directly in your code, which indeed it could be, it would make the code less readable and your file more messy.
If you dont want to place the file in the same directory, simply specify the full file path. E.g. file_get_contents("this/dir/here/test.json");
You can read about how json_decode works here, its essential we pass it the true parameter to make our arrays associative.
You can extract your need array from JSON data. You can use a loop too to read all your data inside the order array.
$array = json_decode($json, true);
$verbose = $array['data'];
$orderArray = $verbose['order'];
print_r($orderArray);
echo $orderArray['id'];
echo $orderArray['ip_address'];

How to read context parameters using php webhook in dialogflow

Need help with the following I writing a webhook in php, and need the ability to read the context parameters.
Can someone help me to understand how it can be done?
Here is my example JSON:
{
"id": "6e774dc2-2323-42b3-bd3c-ab64930f8b92",
"timestamp": "2017-12-22T21:12:19.094Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "Yes",
"action": "Triage.Triage-yes",
"actionIncomplete": false,
"parameters": {},
"contexts": [
{
"name": "triage-followup",
"parameters": {
"triagecriteria": [],
"roomEntity.original": "",
"roomname": "300",
"roomnames.original": "living",
"roomid": "200",
"context": "",
"roomnames": [
"living"
],
"counter": "400",
"roomEntity": "100",
"triagecriteria.original": ""
},
"lifespan": 3
}
],
"metadata": {
"intentId": "ecd4a2e5-65a0-41b2-ac72-edcf4d2e73f2",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 203,
"intentName": "Triage - yes"
},
"fulfillment": {
"speech": "Yes",
"source": "agent",
"displayText": "No",
"messages": [
{
"type": 0,
"speech": "Yes"
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "db8c1a4e-fa0c-4257-a536-78b63879eef9"
}
I want to be able to refer to [results][Contexts][Parameters]
I am using
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true, 512, JSON_BIGINT_AS_STRING);
and trying to access the value as $update["results"]["Contexts"]["Parameters"]["roomid"]
The names are case sensitive, and you need to be careful about trailing "s"es. Since some of the items are numerically indexed arrays, you'll need to include that as part of the index. Try
$update["result"]["contexts"][0]["parameters"]["roomid"]

Stripe API JSON returns null

Using the Stripe API in PHP all attempts to pull a value off of it is returning null, r not displaying a result at all. I've tried
$customers = \Stripe\Customer::all();
$customers_json = $customers->__toJSON();
json_decode($customers_json);
echo $customers_json->data->id;
and also
$customers = \Stripe\Customer::all();
$customer = $customers->__toArray(true);
echo $customer["data"]["id"];
but each time both result in a blank echo. However, when I just output the original variable without parsing it to JSON or anything, it returns a string full of JSON values, just not parsed. The output of just raw $customers is
Stripe\Collection JSON: { "object": "list", "has_more": false, "url": "\/v1\/customers", "data": [ { "id": "cus_6u32tOQ6MRXuqm", "object": "customer", "created": 1441114587, "livemode": false, "description": "test customer", "email": "test#respice.xyz", "shipping": null, "delinquent": false, "metadata": [ ], "subscriptions": { "object": "list", "total_count": 0, "has_more": false, "url": "\/v1\/customers\/cus_6u32tOQ6MRXuqm\/subscriptions", "data": [ ] }, "discount": null, "account_balance": 0, "currency": null, "sources": { "object": "list", "total_count": 0, "has_more": false, "url": "\/v1\/customers\/cus_6u32tOQ6MRXuqm\/sources", "data": [ ] }, "default_source": null } ] }
The issue is that the data field is not an object, but an array of objects. Sticking with the $customer = $customers->__toArray(true); method, you should try the following:
echo $customer['data'][0]['id'];
If you wish to iterate through all customers, try doing this:
foreach($customer['data'] as $currentCustomerData){
// do stuff here
}

Categories