PHP - JSON decode - php

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

Related

JSON data using foreach loop in php and save to database

I get a list of invoices through api. See:
<?php
$url = "https://app.domain.tld/api/v2/accounts/censored/invoices.json?status=uncollectible";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"User-Agent: YourApp (yourname#example.com)",
"Authorization: Basic censored==",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
echo $resp = curl_exec($curl);
curl_close($curl);
?>
This data will be returned to me in JSON:
[{
"id": 23487088,
"custom_id": null,
"proforma": false,
"partial_proforma": false,
"number": "2022-05-0008",
"number_format_id": 363568,
"variable_symbol": "2022050008",
"your_name": "Censored s.r.o.",
"your_street": "Street 1801/22",
"your_street2": null,
"your_city": "Praha",
"your_zip": "10900",
"your_country": "CZ",
"your_registration_no": "00055222",
"your_vat_no": "CZ00055222",
"your_local_vat_no": null,
"client_name": "Firma s.r.o.",
"client_street": "Street 508/2",
"client_street2": null,
"client_city": "Prague",
"client_zip": "111 22",
"client_country": "CZ",
"client_registration_no": "0000000",
"client_vat_no": "",
"client_local_vat_no": "",
"subject_id": 14471217,
"subject_custom_id": null,
"generator_id": null,
"related_id": null,
"correction": false,
"correction_id": null,
"paypal": false,
"gopay": false,
"token": "zuqpytRSBg",
"status": "uncollectible",
"order_number": "",
"issued_on": "2022-05-13",
"taxable_fulfillment_due": "2022-05-13",
"due": 7,
"due_on": "2022-05-20",
"sent_at": null,
"paid_at": null,
"reminder_sent_at": null,
"accepted_at": null,
"cancelled_at": null,
"webinvoice_seen_at": null,
"note": "",
"footer_note": "Společnost je zapsána v obchodním rejstříku vedeném Městským soudem v Praze oddíl C, vložka 000000.",
"private_note": null,
"tags": [],
"bank_account": "0000000000/2010",
"iban": "CZ000000000000000000000",
"swift_bic": "FIOBCZPPXXX",
"show_already_paid_note_in_pdf": false,
"payment_method": "bank",
"hide_bank_account": false,
"currency": "CZK",
"exchange_rate": "1.0",
"language": "cz",
"transferred_tax_liability": false,
"eu_electronic_service": false,
"oss": "disabled",
"vat_price_mode": "without_vat",
"supply_code": "",
"subtotal": "3000.0",
"total": "3630.0",
"native_subtotal": "3000.0",
"native_total": "3630.0",
"remaining_amount": "3630.0",
"remaining_native_amount": "3630.0",
"paid_amount": "0.0",
"eet": false,
"eet_cash_register": null,
"eet_store": null,
"eet_records": [],
"lines": [{
"id": 52921163,
"name": "IT services",
"quantity": "1.0",
"unit_name": "",
"unit_price": "3000.0",
"vat_rate": 21,
"unit_price_without_vat": "3000.0",
"unit_price_with_vat": "3630.0"
}],
"attachment": null,
"html_url": "https://app.fakturoid.cz/censored/invoices/23487088",
"public_html_url": "https://app.fakturoid.cz/censored/p/zuqpytRSBg/2022-05-0008",
"url": "https://app.fakturoid.cz/api/v2/accounts/censored/invoices/23487088.json",
"pdf_url": "https://app.fakturoid.cz/api/v2/accounts/censored/invoices/23487088/download.pdf",
"subject_url": "https://app.fakturoid.cz/api/v2/accounts/censored/subjects/14471217.json",
"created_at": "2022-05-21T16:27:32.488+02:00",
"updated_at": "2022-05-21T16:27:35.464+02:00"
}, {
"id": 23487082,
"custom_id": null,
"proforma": false,
"partial_proforma": false,
"number": "2022-05-0007",
"number_format_id": 363568,
"variable_symbol": "2022050007",
"your_name": "censored s.r.o.",
"your_street": "censored",
"your_street2": null,
"your_city": "Praha",
"your_zip": "10900",
"your_country": "CZ",
"your_registration_no": "00055222",
"your_vat_no": "CZ00055222",
"your_local_vat_no": null,
"client_name": "Firma s.r.o.",
"client_street": "Street 508/2",
"client_street2": null,
"client_city": "Prague",
"client_zip": "111 22",
"client_country": "CZ",
"client_registration_no": "0000000",
"client_vat_no": "",
"client_local_vat_no": "",
"subject_id": 14471217,
"subject_custom_id": null,
"generator_id": null,
"related_id": null,
"correction": false,
"correction_id": null,
"paypal": false,
"gopay": false,
"token": "7xIDMf64iQ",
"status": "uncollectible",
"order_number": "",
"issued_on": "2022-05-04",
"taxable_fulfillment_due": "2022-05-04",
"due": 1,
"due_on": "2022-05-05",
"sent_at": null,
"paid_at": null,
"reminder_sent_at": null,
"accepted_at": null,
"cancelled_at": null,
"webinvoice_seen_at": null,
"note": "",
"footer_note": "Společnost je zapsána v obchodním rejstříku vedeném Městským soudem v Praze oddíl C, vložka 000000.",
"private_note": null,
"tags": [],
"bank_account": "000000000/2010",
"iban": "CZ000000000000000000000",
"swift_bic": "FIOBCZPPXXX",
"show_already_paid_note_in_pdf": false,
"payment_method": "bank",
"hide_bank_account": false,
"currency": "CZK",
"exchange_rate": "1.0",
"language": "cz",
"transferred_tax_liability": false,
"eu_electronic_service": false,
"oss": "disabled",
"vat_price_mode": "without_vat",
"supply_code": "",
"subtotal": "5000.0",
"total": "6050.0",
"native_subtotal": "5000.0",
"native_total": "6050.0",
"remaining_amount": "6050.0",
"remaining_native_amount": "6050.0",
"paid_amount": "0.0",
"eet": false,
"eet_cash_register": null,
"eet_store": null,
"eet_records": [],
"lines": [{
"id": 52921141,
"name": "IT services",
"quantity": "1.0",
"unit_name": "",
"unit_price": "5000.0",
"vat_rate": 21,
"unit_price_without_vat": "5000.0",
"unit_price_with_vat": "6050.0"
}],
"attachment": null,
"html_url": "https://app.fakturoid.cz/censored/invoices/23487082",
"public_html_url": "https://app.fakturoid.cz/censored/p/7xIDMf64iQ/2022-05-0007",
"url": "https://app.fakturoid.cz/api/v2/accounts/censored/invoices/23487082.json",
"pdf_url": "https://app.fakturoid.cz/api/v2/accounts/censored/invoices/23487082/download.pdf",
"subject_url": "https://app.fakturoid.cz/api/v2/accounts/censored/subjects/14471217.json",
"created_at": "2022-05-21T16:25:51.916+02:00",
"updated_at": "2022-05-21T16:26:54.323+02:00"
}]
The problem is that I can't throw it into a nice boostrap table, columns using PHP and possibly save it to a database. I tried it this way, but I did not meet with success.
<?php
$data = json_decode($resp->data, true);
foreach ($data as $key => $value) {
$invoice_id = $value['array']['id']; // id invoice
$invoice_status = $value['array']['status']; // paid, unpaid, uncollectible etc...
$invoice_price = $value['array']['total']; // total price with VAT
}
?>
But I'm not successful. I'm getting a error:
Error: Trying to get property 'data' of non-object
I'm at the end, please help
please use this php code, your array contains objects
$data = json_decode($resp);
foreach ($data as $key => $value) {
$invoice_id = $value->id; // id invoice
$invoice_status = $value->status; // paid, unpaid, uncollectible etc...
$invoice_price = $value->total; // total price with VAT
}

One to many relationship in two JSON arrays, lookup results in PHP

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;
}
}

PHP Nested JSON Array reading

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");

How to redirect to URL received from JSON response using PHP

I using process.php to post to an API and receive the following response
{ "payment_request":
{
"id": "554efa8b701c4021be7310b8916cc30b",
"phone": null,
"email": null,
"buyer_name": null,
"amount": "12",
"purpose": "product-sleek",
"status": "Pending",
"send_sms": false,
"send_email": false,
"sms_status": null,
"email_status": null,
"shorturl": null,
"longurl": "https://www.example.com/#user/554efa8b701c4021be7310b8916cc30b",
"redirect_url": "https://example.com/order-received/",
"webhook": null,
"created_at": "2016-04-06T05:01:04.042Z",
"modified_at": "2016-04-06T05:01:04.042Z",
"allow_repeated_payments": false
},
"success": true
}
Now after receiving the response, I want to redirect the page to the longurl value in the response json, How should I do it?
use json_decode to parse json in array or object and then use header function to redirect it
$json = '{ "payment_request":
{
"id": "554efa8b701c4021be7310b8916cc30b",
"phone": null,
"email": null,
"buyer_name": null,
"amount": "12",
"purpose": "product-sleek",
"status": "Pending",
"send_sms": false,
"send_email": false,
"sms_status": null,
"email_status": null,
"shorturl": null,
"longurl": "https://www.example.com/#user/554efa8b701c4021be7310b8916cc30b",
"redirect_url": "https://example.com/order-received/",
"webhook": null,
"created_at": "2016-04-06T05:01:04.042Z",
"modified_at": "2016-04-06T05:01:04.042Z",
"allow_repeated_payments": false
},
"success": true
}';
$json_array = json_decode($json, true);
$longurl = $json_array['payment_request']['longurl'];
header("Location: $longurl");

Parse Daunting JSON: PHP

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

Categories