iterating a php object - php

I am sure this is a complete noob question but I am trying to iterate through an api response from stripe.com and I am able to echo out the array in php to be something like this:
{ "count": 3,
"data": [ { "amount": 29900,
"object": "plan",
"interval": "month",
"livemode": false,
"currency": "usd",
"name": "vb Group unlimited",
"id": "vb-std-group2" },
{ "amount": 9900,
"object": "plan",
"interval": "year",
"livemode": false,
"currency": "usd",
"name": "vb Group to 20",
"id": "vb-std-group" },
{ "amount": 1900,
"object": "plan",
"interval": "year",
"livemode": false,
"currency": "usd",
"name": "vb-Individual",
"id": "vb-std-individual" }
]
}
What I'm trying to do is echo out the "data" array info. Thanks for any insight.

The string you have is JSON encoded. Decode it using json_decode into a PHP object, say $obj. Then, $obj['data'] is an array. Iterate over it using a foreach loop.
foreach($obj['data'] as $key=>$object)
foreach($object as $key=>$value)
echo $key . " : " . $value;

Try something like this:
$reponseData = $response['data'];
foreach($reponseData as $eachDataObj)
{
foreach($eachDataObj as $key => $val)
{
echo $key . " => ".$val;
}
}
This assumes that $response is already an object, if it is actually just TEXT then you have to use
$response = json_decode($response);

Check this out it would help you
$myjson = '{ "count": 3,
"data": [ { "amount": 29900,
"object": "plan",
"interval": "month",
"livemode": false,
"currency": "usd",
"name": "vb Group unlimited",
"id": "vb-std-group2" },
{ "amount": 9900,
"object": "plan",
"interval": "year",
"livemode": false,
"currency": "usd",
"name": "vb Group to 20",
"id": "vb-std-group" },
{ "amount": 1900,
"object": "plan",
"interval": "year",
"livemode": false,
"currency": "usd",
"name": "vb-Individual",
"id": "vb-std-individual" }
]
}';
$data =json_decode($myjson);
$arrData = get_object_vars($data);
foreach($arrData as $key=>$value){
$arrData[$key] = $value;
}
//print_r($arrData['data']);
foreach($arrData['data'] as $ke=>$va):
foreach($va as $k=>$v):
echo $k."-".$v."<br/>";
endforeach;
endforeach;

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']);

php how to extract values from an array

I have an array which I was able to get some details from my results like this:
$result["transaction"];
when doing this the follow is displayed:
{ "id": "wt13LbKmJ2",
"location_id": "EYGMFA",
"created_at": "2017-07-01T07:32:57Z",
"tenders":
[ { "id": "C6xMF",
"location_id": "MFA",
"transaction_id": "NvDAOOA9",
"created_at": "2017-07-01T07:32:57Z",
"note": "Offering",
"amount_money": { "amount": 100, "currency": "USD" }, "processing_fee_money": { "amount": 33, "currency": "USD" },
"customer_id": "14QEJXXM5TX",
"type": "CARD",
"card_details": { "status": "CAPTURED",
"card": { "brand": "VI", "last_4": "0000" },
"entry_method": "ON_FILE"
} } ],
"product": "EXTERNAL_API" }
How can I get my array to only display "100" where it say "amount":100
If I use:
$result["transaction"]["id"];
it will display only the id but I can't get the amount to display.
Use the following to check ur data and use last line like echo $data->tenders[0]->amount_money->amount;
<?php
$string='{ "id": "wt13LbKmJ2", "location_id": "EYGMFA", "created_at": "2017-07-01T07:32:57Z", "tenders": [ { "id": "C6xMF", "location_id": "MFA", "transaction_id": "NvDAOOA9", "created_at": "2017-07-01T07:32:57Z", "note": "Offering", "amount_money": { "amount": 100, "currency": "USD" }, "processing_fee_money": { "amount": 33, "currency": "USD" }, "customer_id": "14QEJXXM5TX", "type": "CARD", "card_details": { "status": "CAPTURED", "card": { "brand": "VI", "last_4": "0000" }, "entry_method": "ON_FILE" } } ], "product": "EXTERNAL_API" }';
$data=json_decode($string);
echo '<pre>';
print_r(json_decode($string));
echo '</pre>';
echo $data->id.'<br>';
echo $data->tenders[0]->id;
echo $data->tenders[0]->amount_money->amount;
?>
strong text
$result['transaction']['tenders'][0]['amount_money']['amount']
First you need to change $result object to array then fetch the data
do like this
$result=json_decode(json_encode($result,true),true);
Then
$result['transaction']['tenders'][0]['amount_money']['amount']
I thing it will help you.

Accessing plan id during Stripe response

Here the json sent by Stripe to get invoices status:
Stripe\Collection JSON: {
...
"data" => [
[0] => Stripe\Invoice JSON: {
...
"lines": {
"data": [
{
...
"subscription": null,
"quantity": 1,
"plan": {
"interval": "month",
"name": "X-Large - 12 mois",
"created": 1435711579,
"amount": 52800,
"currency": "cad",
"id": "X-LARGE_12M",
"object": "plan",
"livemode": false,
"interval_count": 12,
"trial_period_days": null,
"metadata": {
},
"statement_descriptor": null
},
...
}
],
...
},
...
}
]
}
The json response can be found here:
https://stripe.com/docs/api#list_customer_invoices
I would like to access to the plan id (i.e.: X-LARGE_12M).
So I tried:
$invoice->lines->data->plan->id
But it doesn't work.
It works for others fields.
Any reason why ?
Thanks.
"data": [
{
The data element is an array of objects. So you'd need something like
foreach($invoice->lines->data as $data) {
echo $data->plan->id, "\r\n";
}

extract data value from nested JSON

I am trying to get some specific fields out of this Json.
fn({
"processingDurationMillis": 454,
"authorisedAPI": true,
"success": true,
"airline": "MH",
"validCreditCards": [
"AX",
"CA",
"VI"
],
"paypal": true,
"outboundOptions": [
{
"optionId": 0,
"flights": [
{
"flightNumber": "0066",
"departureAirport": {
"code": "KUL",
"name": "Kuala Lumpur Intl",
"city": "Kuala Lumpur",
"country": "Malaysia",
"timezone": "Asia/Kuala_Lumpur",
"lat": 2.745578,
"lng": 101.709917,
"terminal": null,
"gate": null
},
"arrivalAirport": {
"code": "ICN",
"name": "Incheon Intl",
"city": "Seoul",
"country": "South Korea",
"timezone": "Asia/Seoul",
"lat": 37.469075,
"lng": 126.450517,
"terminal": null,
"gate": null
},
"marketingAirline": "MH",
"mealIndicator": "M",
"allowedSsrs": {
},
"operatingAirline": null,
"equipment": "333",
"equipmentName": "Airbus A330-300",
"flightRPH": 10101,
"comments": [
"MH CODESHARE WITH KE"
],
"depScheduled": "2015-04-28T23:30:00.000+08:00",
"arrScheduled": "2015-04-29T07:10:00.000+09:00",
"depEstimated": null,
"depActual": null,
"arrEstimated": null,
"arrActual": null,
"eligibleForEticketing": true,
"cabin": "ECONOMY",
"fareMarketingType": "BASIC",
"rbd": "N",
"seatsAvailable": 9,
"durationMinutes": 400,
"minutesToScheduledFlightDeparture": 6486
}
],
"stopOvers": [
],
"fareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "1214.95",
"currencyCode": "MYR"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "68.90",
"taxes": [
{
"code": "MY",
"amount": "65.00",
"currency": "MYR"
},
{
"code": "D8",
"amount": "3.90",
"currency": "MYR"
}
]
}
],
"journeyFare": "1214.95",
"totalTripFare": "1283.90",
"fareCurrency": "MYR"
},
"magicString": "2t2qi8oNXWkrDR75zYDrk9+3wNaJBzHyK1ftoR/VZPVgHO+EFTkh8DMg5WUl1ap7VjwBsnhD2gFxAwBbHhY0+k0lp7BUvSoYSKg6S6u4ZkvbIWMktl+lHgcKl46vht9//2dZVJvH4D7WJvnJTtK5O4TWNrkiTmEdHp55yRmjwWfsgNswOIMXoWrZj3OUJ4DH4POJ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bxSFCBga7yIPWx/NZdGjUYTuiJ9KZ7W2dKLhF6XDU5mWOV7XwMRzkyschEnjSzQWGjTTftEIiNI1V1M2bhFwc92JkfVFxwXCg==",
"seatsAvailable": [
9
],
"corporateAccount": false,
"flightCanBeHeld": true,
"durationMinutes": 400,
"gaFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "1214.95",
"currencyCode": "MYR"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "68.90",
"taxes": [
{
"code": "MY",
"amount": "65.00",
"currency": "MYR"
},
{
"code": "D8",
"amount": "3.90",
"currency": "MYR"
}
]
}
],
"journeyFare": "1214.95",
"totalTripFare": "1283.90",
"fareCurrency": "MYR"
},
"adobeFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "336.66",
"currencyCode": "USD"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "19.09",
"taxes": [
{
"code": "MY",
"amount": "18.01",
"currency": "USD"
},
{
"code": "D8",
"amount": "1.08",
"currency": "USD"
}
]
}
],
"journeyFare": "336.66",
"totalTripFare": "355.77",
"fareCurrency": "USD"
},
"userAgentFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "336.66",
"currencyCode": "USD"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "19.09",
"taxes": [
{
"code": "MY",
"amount": "18.01",
"currency": "USD"
},
{
"code": "D8",
"amount": "1.08",
"currency": "USD"
}
]
}
],
"journeyFare": "336.66",
"totalTripFare": "355.77",
"fareCurrency": "USD"
},
"eligibleForeTicketing": true,
"lowestSeatCount": 9,
"directFlight": true
}
],
"departureAirport": {
"code": "KUL",
"name": "Kuala Lumpur Intl",
"city": "Kuala Lumpur",
"country": "Malaysia",
"timezone": "Asia/Kuala_Lumpur",
"lat": 2.745578,
"lng": 101.709917,
"terminal": null,
"gate": null
},
"arrivalAirport": {
"code": "ICN",
"name": "Incheon Intl",
"city": "Seoul",
"country": "South Korea",
"timezone": "Asia/Seoul",
"lat": 37.469075,
"lng": 126.450517,
"terminal": null,
"gate": null
},
"apiRequired": true,
"fareRules": [
{
"id": 50,
"order": 1,
"priority": 0,
"code": "Basic",
"name": "MHbasic",
"value": "Economy Class Fares",
"listFareRules": [
{
"id": 130,
"order": 0,
"code": "",
"name": "Discount level",
"value": "Up to 65%"
},
{
"id": 140,
"order": 1,
"code": "",
"name": "Where to buy",
"value": "All channels"
},
{
"id": 150,
"order": 2,
"code": "",
"name": "Advance purchase",
"value": "Applies"
},
{
"id": 160,
"order": 3,
"code": "",
"name": "Payment",
"value": "Ticket dateline applies"
},
{
"id": 170,
"order": 4,
"code": "",
"name": "Baggage allowance",
"value": "2pc/30kg"
},
{
"id": 180,
"order": 5,
"code": "",
"name": "Advance seat selection",
"value": "Not allowed"
},
{
"id": 190,
"order": 6,
"code": "",
"name": "Enrich miles",
"value": "Nil"
},
{
"id": 200,
"order": 7,
"code": "",
"name": "Change of booking",
"value": "Not allowed"
},
{
"id": 210,
"order": 8,
"code": "",
"name": "Upgrade",
"value": "Not allowed"
},
{
"id": 220,
"order": 9,
"code": "",
"name": "Stand by at the airport",
"value": "For a fee"
},
{
"id": 220,
"order": 10,
"code": "",
"name": "No show",
"value": "Penalty applies"
},
{
"id": 230,
"order": 11,
"code": "",
"name": "Refund",
"value": "For a fee"
}
],
"listFareNotes": [
{
"id": 10,
"order": 0,
"code": "",
"name": "Important Notice",
"value": ""
},
{
"id": 15,
"order": 1,
"code": "",
"name": "",
"value": ""
},
{
"id": 20,
"order": 2,
"code": "",
"name": "1.",
"value": "Generic attributes shown only applies to MH operated flights. MH3000-3999, MH5200-5999 and MH9000-9999 Series flights are subject to their own rules. Please contact MH Call Center or ticket offices for actual fare rules."
},
{
"id": 30,
"order": 3,
"code": "",
"name": "2.",
"value": "For transpacific and transatlantic flights, the following baggage allowances apply: Economy - 2 pieces (23kg each piece), First and Business - 2 pieces (32kg each piece)."
},
{
"id": 50,
"order": 5,
"code": "",
"name": "3.",
"value": "Upgrade, standby at the airport and refund fees for specific routes can be obtained from subsequent booking pages."
},
{
"id": 60,
"order": 6,
"code": "",
"name": "4.",
"value": "Standby at the airport denotes the same day for an earlier flight."
},
{
"id": 70,
"order": 7,
"code": "",
"name": "5.",
"value": "Fare rules shown are indicative only. Please call our Contact Center to check the detailed fare rules."
},
{
"id": 80,
"order": 8,
"code": "",
"name": "",
"value": "Should there be any discrepancy between the above information and the terms and conditions (T&C) published in the fare rules, then the T&C in the fare rules shall prevail."
}
]
}
],
"Errors": [
],
"Warnings": [
]
})
i want extract flight number, depScheduled, arrScheduled and journey fare from the above json.
here are my code:
$json2 = json_decode($json,true);
$result= array();
foreach ($json2['outboundOptions']['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
print_r($result);
The code above return me a error, "Invalid argument supplied for foreach()".I searched around, but still have not found the solution yet..
It is giving you that error because outboundOptions is an array of objects. What you want is to access the first object:
foreach ($json2['outboundOptions'][0]['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
Also, remove the trailing comma (,) from your ] at the end as that causes invalid json.
You can check if your json is valid by going to jsonlint.com
Working Example
Update as per your comment
To get all the flights, change your foreach loop to this:
foreach ($json3['outboundOptions'] as $flight) {
foreach($flight['flights'] as $theentity) {
$result[] = $theentity['flightNumber'];
}
}
Example
remove the trailing ',' near the very end of your json.
change your code, add a [0] before ['flights']
$json2 = json_decode($json,TRUE);
$result= array();
foreach ($json2['outboundOptions'][0]['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
print_r($result);

How can I get this Json value in Stripe Invoice?

I am able to retrieve the first 4 values fine, but $item_name is eluding me. What is wrong with the syntax I'm using to retrieve the plan: name: "LITE" value
this is my php - the first 4 return fine but $item_name returns invalid.
$customer = $event_json->data->object->customer;
$amount = $event_json->data->object->total;
$period_end = $event_json->data->object->period_end;
$paid = $event_json->data->object->paid;
$item_name = $event_json->data->object->lines->data->plan->name;
and this is what is being sent from Stripe
{
"id": "evt_1CTCF3tibBeC2y",
"created": 1359565368,
"livemode": false,
"type": "invoice.payment_succeeded",
"data": {
"object": {
"period_end": 1359565367,
"charge": "ch_1CTCMvOgHE1Q9K",
"discount": null,
"period_start": 1359565367,
"livemode": false,
"customer": "cus_1CTCYQNoghibwb",
"amount_due": 7500,
"lines": {
"count": 1,
"object": "list",
"url": "/v1/invoices/in_1CTCCBbENUpsE6/lines",
"data": [
{
"type": "subscription",
"livemode": false,
"period": {
"end": 1391101367,
"start": 1359565367
},
"object": "line_item",
"proration": false,
"plan": {
"trial_period_days": null,
"livemode": false,
"interval": "year",
"object": "plan",
"name": "LITE",
"amount": 7500,
"currency": "usd",
"id": "LITE",
"interval_count": 1
},
Data is an array:
$item_name = $event_json->data->object->lines->data[0]->plan->name;
Right?

Categories