Parse Daunting JSON: PHP - 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

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
}

How to get json output in php from url and get specific result using foreach

First of all I don't really know how to get the result of json which is so much complicated like this:
{
"SearchTime": 190,
"TotalTime": 190,
"SuggestedResponseType": "Person",
"ResultList": [
{
"__type": "ContactResult",
"TotalCount": 57079,
"Type": "Person",
"Contacts": [
{
"UnitId": 459551,
"Id": "459551S1",
"Name": "John d",
"VisitationAddress": "Lauvha 7, 87820",
"PostAddress": null,
"Value": "74 00 00 00",
"ValueType": "Phone",
"Distance": null,
"Rank": 0,
"BusinessName": null,
"Coordinate": {
"Lat": 64.4595741,
"Lon": 11.55081
},
"Logo": null,
"ContactPoints": [
{
"DisplayValue": "911 00 000",
"Indent": 2,
"Label": "Mobiltelefon",
"MainInfo": false,
"Type": "MobilePhone",
"Value": "91000000"
}
],
"FirstName": null,
"LastName": null,
"OrganizationNumber": null,
"Address": {
"PostAddress": null,
"StreetAddress": {
"CityArea": null,
"Coordinate": {
"Lat": 94.4595741,
"Lon": 71.55081
},
"County": "Tr\u00c3\u00b8ndelag",
"DisplayValue": "Lauvha 7 87820 Spilm",
"Entrance": "",
"HouseNumber": "7",
"Houses": null,
"Municipal": "Namsos",
"PostArea": "Spilm",
"PostCode": "87820",
"Street": "Lauvha"
}
},
"Products": null,
"ProfilePictures": null,
"ContactType": "Person"
},
{
"UnitId": 0,
"Id": "Footer",
"Name": "Vis flere treff",
"VisitationAddress": null,
"PostAddress": null,
"Value": "{\"q\":\"john\",\"type\":\"p\",\"start\":1,\"page\":2}",
"ValueType": null,
"Distance": null,
"Rank": 0,
"BusinessName": null,
"Coordinate": null,
"Logo": null,
"ContactPoints": null,
"FirstName": null,
"LastName": null,
"OrganizationNumber": null,
"Address": null,
"Products": null,
"ProfilePictures": null,
"ContactType": null
}
]
}
],
"Stunts": null
}
Next: How can i get the output: name, VisitationAddress and value from (ContactPoints)to be in correct format using foreach
and rid the
"Name": "Vis flere treff",
"Value": "{\"q\":\"john\",\"type\":\"p\",\"start\":1,\"page\":2}",
in the last line.
You'll need to read up on how to interact with objects and arrays in PHP.
$object->property, $array['key'], $object->array_property[$index]->key, etc.
For your particular case, you need to get your JSON using cURL or file_get_contents() or whatever other method you want. Then you need to decode the response with json_decode().
Once you have your JSON object it's just a matter of checking to see if values exist and outputting them however you want. Notice there are a bunch of arrays inside objects, but something like the following will get you started
<?php
$response = file_get_contents( 'https://zabihullah.com/veg/example.json' );
//$response = '{"SearchTime":190,"TotalTime":190,"SuggestedResponseType":"Person","ResultList":[{"__type":"ContactResult","TotalCount":57079,"Type":"Person","Contacts":[{"UnitId":459551,"Id":"459551S1","Name":"John d","VisitationAddress":"Lauvha 7, 87820","PostAddress":null,"Value":"74 00 00 00","ValueType":"Phone","Distance":null,"Rank":0,"BusinessName":null,"Coordinate":{"Lat":64.4595741,"Lon":11.55081},"Logo":null,"ContactPoints":[{"DisplayValue":"911 00 000","Indent":2,"Label":"Mobiltelefon","MainInfo":false,"Type":"MobilePhone","Value":"91000000"}],"FirstName":null,"LastName":null,"OrganizationNumber":null,"Address":{"PostAddress":null,"StreetAddress":{"CityArea":null,"Coordinate":{"Lat":94.4595741,"Lon":71.55081},"County":"Trøndelag","DisplayValue":"Lauvha 7 87820 Spilm","Entrance":"","HouseNumber":"7","Houses":null,"Municipal":"Namsos","PostArea":"Spilm","PostCode":"87820","Street":"Lauvha"}},"Products":null,"ProfilePictures":null,"ContactType":"Person"},{"UnitId":0,"Id":"Footer","Name":"Vis flere treff","VisitationAddress":null,"PostAddress":null,"Value":"{\"q\":\"john\",\"type\":\"p\",\"start\":1,\"page\":2}","ValueType":null,"Distance":null,"Rank":0,"BusinessName":null,"Coordinate":null,"Logo":null,"ContactPoints":null,"FirstName":null,"LastName":null,"OrganizationNumber":null,"Address":null,"Products":null,"ProfilePictures":null,"ContactType":null}]}],"Stunts":null}';
$json = json_decode( $response );
foreach( $json->ResultList[0]->Contacts as $contact ){
//var_dump( $contact );
if( $contact->Name == 'Vis flere treff' ) continue;
if( !empty( $contact->Name ) ) echo "Name: {$contact->Name}\r\n";
if( !empty( $contact->VisitationAddress ) ) echo "Address: {$contact->VisitationAddress}\r\n";
if( !empty( $contact->Value ) ) echo "Value: ". str_replace(' ', '', $contact->Value) ."\r\n";
echo "\r\n";
}
The result of that is the following:
Name: John d
Address: Lauvha 7, 87820
Value: 91000000
Name: Vis flere treff
You can see an example here: http://sandbox.onlinephpfunctions.com/code/ad6aa7fffaf42a32cb8f5568acb24c157c612467

Remove JSON Block with PHP

I have two JSON Files which I merge with a PHP Script. My PHP script looks like this:
<?php
header('Content-Type: application/json');
$a = file_get_contents("https://example.com/a.json", false);
$b = file_get_contents("https://example.com/b.json", false);
$merge = json_encode(array_merge(
json_decode($a, true),
json_decode($b, true)
));
echo $merge;
?>
My Output looks like this:
[{
"id": 1141,
"iid": 167,
"project_id": 17,
"title": "test",
"description": "test",
"state": "opened",
"created_at": "2018-02-19T13:46:38.751Z",
"updated_at": "2018-02-19T14:32:46.061Z",
"closed_at": null,
"labels": [],
"milestone": null,
"assignees": [],
"author": {
"id": 19,
"state": "active"
},
"assignee": null,
"user_notes_count": 0,
"upvotes": 0,
"downvotes": 0,
"due_date": null,
"confidential": false,
"discussion_locked": null,
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
}
}, {
"id": 1140,
"iid": 166,
"project_id": 16,
"title": "test2",
"description": "test2",
"state": "opened",
"created_at": "2018-02-19T11:01:00.729Z",
"updated_at": "2018-02-19T11:01:00.729Z",
"closed_at": null,
"labels": [],
"milestone": null,
"assignees": [{
"id": 5,
"state": "active"
}],
"author": {
"id": 5,
"state": "active"
},
"assignee": {
"id": 5,
"state": "active"
},
"user_notes_count": 0,
"upvotes": 0,
"downvotes": 0,
"due_date": null,
"confidential": false,
"discussion_locked": null,
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
}
}, {
"id": 1136,
"iid": 165,
"project_id": 17,
"title": "test3",
"description": "test3",
"state": "opened",
"created_at": "2018-02-16T15:36:22.712Z",
"updated_at": "2018-02-16T15:36:22.712Z",
"closed_at": null,
"labels": [],
"milestone": null,
"assignees": [{
"id": 5,
"state": "active"
}],
"author": {
"id": 1,
"state": "active"
},
"assignee": {
"id": 5,
"state": "active"
},
"user_notes_count": 0,
"upvotes": 0,
"downvotes": 0,
"due_date": null,
"confidential": false,
"discussion_locked": null,
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
}
}]
Now I want to remove each block with "project_id": 16. How can i remove every Block with "project_id": 16?
So i would like to remove this Block. And everyone else with "project_id": 16, if there were any more.
{
"id": 1140,
"iid": 166,
"project_id": 16,
"title": "test2",
"description": "test2",
"state": "opened",
"created_at": "2018-02-19T11:01:00.729Z",
"updated_at": "2018-02-19T11:01:00.729Z",
"closed_at": null,
"labels": [],
"milestone": null,
"assignees": [{
"id": 5,
"state": "active"
}],
"author": {
"id": 5,
"state": "active"
},
"assignee": {
"id": 5,
"state": "active"
},
"user_notes_count": 0,
"upvotes": 0,
"downvotes": 0,
"due_date": null,
"confidential": false,
"discussion_locked": null,
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
}
},
I'm grateful for any help.
Here a little snippet
$merge = array_filter($merge, function($item){ return $item['project_id'] != 16 })

Recursive Function Not Finding Nested Items

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) {

Print value from inside an object

I have really have troubles trying to work out why this is not working, and it seems like it should be easy, but just cannot seem to get it.
All I am looking to do is grab the sku field (which is VBP-01 below).
{
"variants": [
{
"id": 2314578,
"created_at": "2014-07-29T07:22:18.921Z",
"updated_at": "2015-05-21T15:42:42.136Z",
"product_id": 1188647,
"default_ledger_account_id": null,
"buy_price": "124.0",
"committed_stock": "0",
"incoming_stock": "3",
"composite": false,
"description": null,
"is_online": false,
"keep_selling": false,
"last_cost_price": "124.0",
"manage_stock": true,
"max_online": null,
"moving_average_cost": "124",
"name": "Lanparte battery pinch VBP-01",
"online_ordering": false,
"opt1": null,
"opt2": null,
"opt3": null,
"position": 1,
"product_name": "Lanparte V-Mount Battery Pinch",
"product_status": "active",
"product_type": null,
"retail_price": "0.0",
"sellable": true,
"sku": "VBP-01",
"status": "active",
"stock_on_hand": "1",
"supplier_code": "VBP-01",
"taxable": true,
"upc": null,
"weight": null,
"wholesale_price": "0.0",
"image_ids": [],
"variant_prices": [
{
"price_list_id": "buy",
"value": "124.0"
},
{
"price_list_id": "retail",
"value": "0.0"
},
{
"price_list_id": "wholesale",
"value": "0.0"
}
],
"locations": [
{
"location_id": 16377,
"stock_on_hand": "1",
"committed": null,
"incoming": "3",
"bin_location": null,
"reorder_point": 3
}
],
"prices": {
"buy": "124.0",
"retail": "0.0",
"wholesale": "0.0"
},
"stock_levels": {
"16377": "1.0"
},
"committed_stock_levels": {},
"incoming_stock_levels": {
"16377": "3.0"
}
}
],
"meta": {
"total": 1
}
}
Currently I using the following code with no luck
$url = "https://api.tradegecko.com/variants?sku=VBP-01";
$data = file_get_contents($url, false, $context);
$json = json_decode($data);
print $json->{'variant'}->{'sku'};
What I am doing wrong?
Just
echo $json->{'variants'}[0]->{'sku'};
In a loop
foreach ($json->variants as $variants) {
echo $variants->sku;
}

Categories