I am trying to combine 2 JSON objects from an API with 2 different id keys.
I have tried some code in php based on my working code in react native(javascript) but rebuilding the code did not work as expected.
sample first JSON:
[{
poiNumberWinter: null,
minAge: null,
maxAge: null,
minSize: 100,
maxSize: null,
minSizeEscort: 1,
id: 1,
titleImageId: 390,
titleImageWinterId: null,
createdAt: "2018-03-14T15:45:47.000Z",
updatedAt: "2019-03-26T10:58:44.000Z",
_titleWinter: null
}]
sample second JSON:
[{
open: false,
poiId: "1",
closing: null,
opening: "2019-08-15 10:00:00",
showTimes: null,
waitTime: null,
updatedAt: "2019-08-15T20:12:40.000Z",
}]
This is what I have tried:
$rideTimesconverted = json_decode($rideTimes);
$metaDataConverted = json_decode($metaData);
$fullRideData = array();
for ($i = 0; $i < count($rideTimesconverted); $i++) {
$test = array_filter($metaDataConverted, function ($item) use (
$i,
$rideTimesconverted
) {
return $item['id'] === (int) $rideTimesconverted[$i]['poiId'];
});
array_push($fullRideData, $rideTimesconverted[$i], $test);
}
based on my React Native code which works perfectly:
let rideTimes = await GetApiData.getRidesTime();
let rideMetaData = await GetApiData.getRidesMetaData();
let fullRideData = [];
for (let i = 0; i < this.state.rideTimes.length; i++) {
fullRideData.push({
...this.state.rideTimes[i],
...this.state.rideMetaData.find(
itmInner =>
itmInner.id ===
parseInt(this.state.rideTimes[i].poiId)
)
});
}
But the results get mixed up really weird:
{
open: false,
poiId: "1",
closing: null,
opening: "2019-08-15 10:00:00",
showTimes: null,
waitTime: null,
createdAt: "2019-08-15T22:18:03.000Z",
updatedRow: "2019-08-15T22:18:03.000Z"
},
[
{
poiNumberWinter: null,
minAge: null,
maxAge: null,
minSize: 100,
maxSize: null,
minSizeEscort: 1,
id: 1,
titleImageId: 390,
titleImageWinterId: null,
createdAt: "2018-03-14T15:45:47.000Z",
updatedAt: "2019-03-26T10:58:44.000Z",
_titleWinter: null
}
],
I want this result, merged on poiId and id being the same:
[{
open: false,
poiId: "1",
closing: null,
opening: "2019-08-15 10:00:00",
showTimes: null,
waitTime: null,
createdAt: "2019-08-15T22:18:03.000Z",
updatedRow: "2019-08-15T22:18:03.000Z"
poiNumberWinter: null,
minAge: null,
maxAge: null,
minSize: 100,
maxSize: null,
minSizeEscort: 1,
id: 1,
titleImageId: 390,
titleImageWinterId: null,
createdAt: "2018-03-14T15:45:47.000Z",
updatedAt: "2019-03-26T10:58:44.000Z",
_titleWinter: null
}]
This function should do the job if I read your question correctly.
$rideTimes = '[{
"poiNumberWinter": null,
"minAge": null,
"maxAge": null,
"minSize": 100,
"maxSize": null,
"minSizeEscort": 1,
"id": 1,
"titleImageId": 390,
"titleImageWinterId": null,
"createdAt": "2018-03-14T15:45:47.000Z",
"updatedAt": "2019-03-26T10:58:44.000Z",
"_titleWinter": null
},
{
"poiNumberWinter": null,
"minAge": null,
"maxAge": null,
"minSize": 100,
"maxSize": null,
"minSizeEscort": 1,
"id": 3,
"titleImageId": 390,
"titleImageWinterId": null,
"createdAt": "2018-03-14T15:45:47.000Z",
"updatedAt": "2019-03-26T10:58:44.000Z",
"_titleWinter": null
}]';
$metaData = '[{
"open": false,
"poiId": "1",
"closing": null,
"opening": "2019-08-15 10:00:00",
"showTimes": null,
"waitTime": null,
"updatedAt": "2019-08-15T20:12:40.000Z"
},
{
"open": false,
"poiId": "2",
"closing": null,
"opening": "2019-08-15 15:00:00",
"showTimes": null,
"waitTime": null,
"updatedAt": "2019-08-15T20:12:40.000Z"
}]';
function someFancyName($arrRideTime, $arrMetaData)
{
$hits = [];
foreach ($arrRideTime as $rTime) {
foreach ($arrMetaData as $mData) {
if ($mData['poiId'] == $rTime['id']) {
$hits[] = array_merge($rTime, $mData);
}
}
}
return $hits;
}
$arrRideTime = json_decode($rideTimes, true);
$arrMetaData = json_decode($metaData, true);
echo '<pre><code>';
var_dump(someFancyName($arrRideTime, $arrMetaData));
echo '</code></pre>';
Related
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"]);
I'm creating an invoice using Stripe's API call. Based on stripe documentation, there is no amount parameters for generated invoice and I always get zero in amount_due.
Another issue is I want to add line items in generate invoice, but there is no places to add line items for generated invoice.
Here is my code;
$params = [
'customer' => $stripeCustomer['stripeCustomerId'],
'auto_advance' => true,
'collection_method' => 'charge_automatically',
'currency' => Str::lower($record['CurrencyCode']),
'metadata' => $metaData,
];
$stripeInvoice = \Stripe\Invoice::create($params);
And stripe return object is here;
{
"id": "in_1M6otQLHPCwYGWEgSQraCHVf",
"object": "invoice",
"account_country": "SG",
"account_name": "Demo",
"account_tax_ids": null,
"amount_due": 0,
"amount_paid": 0,
"amount_remaining": 0,
"application": null,
"application_fee_amount": null,
"attempt_count": 0,
"attempted": false,
"auto_advance": true,
"automatic_tax": {
"enabled": false,
"status": null
},
"billing_reason": "manual",
"charge": null,
"collection_method": "charge_automatically",
"created": 1669094376,
"currency": "sgd",
"custom_fields": null,
"customer": "cus_MqVqznCTTb78Ct",
"customer_address": {
"city": "",
"country": "",
"line1": "",
"line2": "",
"postal_code": "",
"state": ""
},
"customer_email": "john.doe#doe.com",
"customer_name": "John Doe",
"customer_phone": null,
"customer_shipping": null,
"customer_tax_exempt": "none",
"customer_tax_ids": [
],
"default_payment_method": null,
"default_source": null,
"default_tax_rates": [
],
"description": null,
"discount": null,
"discounts": [
],
"due_date": null,
"ending_balance": null,
"footer": null,
"from_invoice": null,
"hosted_invoice_url": null,
"invoice_pdf": null,
"last_finalization_error": null,
"latest_revision": null,
"lines": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/invoices/in_1M6otQLHPCwYGWEgSQraCHVf/lines"
},
"livemode": false,
"metadata": {
"invoiceNumber": "INV-0005",
"invoiceId": "fcca9507-411d-4087-b940-03251402beab"
},
"next_payment_attempt": 1669097976,
"number": null,
"on_behalf_of": null,
"paid": false,
"paid_out_of_band": false,
"payment_intent": null,
"payment_settings": {
"default_mandate": null,
"payment_method_options": null,
"payment_method_types": null
},
"period_end": 1669094376,
"period_start": 1669094376,
"post_payment_credit_notes_amount": 0,
"pre_payment_credit_notes_amount": 0,
"quote": null,
"receipt_number": null,
"rendering_options": null,
"starting_balance": 0,
"statement_descriptor": null,
"status": "draft",
"status_transitions": {
"finalized_at": null,
"marked_uncollectible_at": null,
"paid_at": null,
"voided_at": null
},
"subscription": null,
"subtotal": 0,
"subtotal_excluding_tax": 0,
"tax": null,
"test_clock": null,
"total": 0,
"total_discount_amounts": [
],
"total_excluding_tax": 0,
"total_tax_amounts": [
],
"transfer_data": null,
"webhooks_delivered_at": 1669094376
}
Invoices Create API always creates an empty invoice first, then use Invoice Items Create API to add line items to the invoice later.
You may refer to the doc here for the step-by-step integration: https://stripe.com/docs/invoicing/integration
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");
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) {