json decode error on some requests but not others with Algolia php library - php

I'm seeing the following error:
My params are
array (size=4)
'facets' => string 'Instock.1' (length=9)
'facetFilters' => string 'inStock.1:1' (length=11)
'numericFilters' => string 'itemId!=511283' (length=14)
'getRankingInfo' => int 1
If I remove either getRankingInfo or numericFilters, it works for all requests.
According to the logs in Algolia it's returning results, but i don't get that far on my end for some requests.
One response that causes the error to appear is:
Request
{
"params": "facets=Instock.1&facetFilters=inStock.1%3A1&numericFilters=itemId%21%3D511283&getRankingInfo=1&query=WARBURTON+ORANGE+WRAPPER+800G"
}
Response
{
"hits": [
{
"itemId": 506241,
"name": "Warburton Blue Wrapper 800g",
"slug": "506241-warburton-blue-wrapper",
"brand": "Warburton",
"supplier_name": "Warburtons Bread",
"size": "800G",
"status": "L",
"vat_rate": "0.00",
"popularity": 18992,
"image": "/images/products/506241.jpg",
"thumbnail": "/images/products/506241_thumbnail.jpg",
"barcodes": [
"5010044000039"
],
"branches": [
1,
2,
4,
5,
6
],
"deepestCategory": "07013033337",
"inStock": {
"1": 1,
"2": 0,
"4": 1,
"5": 1,
"6": 1
},
"alternatives": [
],
"objectID": "506241",
"_highlightResult": {
"name": {
"value": "<em>Warburton</em> Blue <em>Wrapper</em> <em>800g</em>",
"matchLevel": "partial",
"matchedWords": [
"warburton",
"wrapper",
"800g"
]
},
"barcodes": [
{
"value": "5010044000039",
"matchLevel": "none",
"matchedWords": [
]
}
]
},
"_rankingInfo": {
"nbTypos": 0,
"firstMatchedWord": 0,
"proximityDistance": 10,
"userScore": 21542,
"geoDistance": 0,
"geoPrecision": 1,
"nbExactWords": 3,
"words": 3
}
},
{
"itemId": 511294,
"name": "Warburton Green Wrapper ",
"slug": "511294-warburton-green-wrapper",
"brand": "Warburton",
"supplier_name": "Warburtons Bread",
"size": "",
"status": "L",
"vat_rate": "0.00",
"popularity": 78098,
"image": "/images/products/511294.jpg",
"thumbnail": "/images/products/511294_thumbnail.jpg",
"barcodes": [
"5010044002347"
],
"branches": [
1,
2,
4,
5,
6
],
"deepestCategory": "07013033337",
"inStock": {
"1":
One that works fine is:
Request body
{
"params": "facets=Instock.1&facetFilters=inStock.1%3A1&numericFilters=itemId%21%3D558471&getRankingInfo=1&query=I+CAN%27T+BELIEVE+IT%27S+NOT+BUTTER+2KG"
}
Response
{
"hits": [
{
"itemId": 581691,
"name": "I Can't Believe Its Not Butter 500g",
"slug": "581691-i-cant-believe-its-not-butter",
"brand": "I Can't Believe",
"supplier_name": "U.lever Bestfoods (chilled)",
"size": "500G",
"status": "L",
"vat_rate": "0.00",
"popularity": 36597,
"image": "/images/products/581691.jpg",
"thumbnail": "/images/products/581691_thumbnail.jpg",
"barcodes": [
"000118039904",
"05000118039904",
"5000241007009"
],
"branches": [
1,
2,
3,
4,
5,
6
],
"deepestCategory": "07015269103",
"inStock": {
"1": 1,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1
},
"alternatives": [
],
"objectID": "581691",
"_highlightResult": {
"name": {
"value": "<em>I</em> <em>Can't</em> <em>Believe</em> <em>Its</em> <em>Not</em> <em>Butter</em> 500g",
"matchLevel": "partial",
"matchedWords": [
"i",
"can",
"t",
"believe",
"it",
"s",
"not",
"butter"
]
},
"barcodes": [
{
"value": "000118039904",
"matchLevel": "none",
"matchedWords": [
]
},
{
"value": "05000118039904",
"matchLevel": "none",
"matchedWords": [
]
},
{
"value": "5000241007009",
"matchLevel": "none",
"matchedWords": [
]
}
]
},
"_rankingInfo": {
"nbTypos": 0,
"firstMatchedWord": 0,
"proximityDistance": 22,
"userScore": 15914,
"geoDistance": 0,
"geoPrecision": 1,
"nbExactWords": 6,
"words": 8
}
},
{
"itemId": 247577,
"name": "I Can't Believe Its Not Butter 250g"

It seems the result set was causing an error with json_decode. When I limited the hitsPerPage to 10 all works fine. So the answer here is to paginate large sets, obvious really.
Thanks to all who read and commented.

Related

Doctrine Issue - Entities not joining correctly

So I'm having a strange problem with Doctrine that I don't understand and need help with. Essentially, I am running quite a complex query due to the nature of my database and its various joins and for some reason the response when I grab try to grab all records from my database is returning my entities incorrectly.
See my doctrine query below:
$subQuery = $this->_em->createQueryBuilder()
->from(Product::class, 'ex')
->select('ppsi.id')
->join('ex.productSpecificationItems', 'ppsi')
->where('ex.id = p.id');
$subQuery = $subQuery->getDQL();
$subQuery2 = $this->_em->createQueryBuilder()
->from(Product::class, 'ex2')
->select('ppoiv.id')
->join('ex2.productOptionItemValues', 'ppoiv')
->where('ex2.id = p.id');
$subQuery2 = $subQuery2->getDQL();
$subQuery3 = $this->_em->createQueryBuilder()
->from(Product::class, 'ex3')
->select('poie.id')
->join('ex3.productOptionItems', 'poie')
->where('ex3.id = p.id');
$subQuery3 = $subQuery3->getDQL();
$qb = $this->createQueryBuilder('p')
->select('p, pc, psc, i, po, poi, poiv, ps, psi')
->join('p.productCategory', 'pc')
->leftJoin('p.productSubCategory', 'psc')
->leftJoin('p.images', 'i')
->leftJoin('p.productOptions', 'po')
->leftJoin('p.productSpecifications', 'ps')
->leftJoin('ps.productSpecificationItems', 'psi', Join::WITH, 'psi.id IN (' . $subQuery. ')')
->leftJoin('po.productOptionItems', 'poi', Join::WITH, 'poi.id IN (' . $subQuery3. ')')
->leftJoin('poi.productOptionItemValue', 'poiv', Join::WITH, 'poiv.id IN (' . $subQuery2. ')')
->addOrderBy('p.id', 'ASC');
The response of this causes some entities to have the productOptionItemValues either listed under the wrong productOptionItem, just causes blank records to return, or doesn't return them at all. See an example below (as a JSON for clarity):
{
"id": 373,
"name": "test",
"code": "test",
"url": "373-test",
"price": "1.00",
"stock": 1,
"description": "<p>fghfgh mnsdbfksdhfjk sd</p>\n",
"live": false,
"createdAt": "2022-03-17T14:45:35+00:00",
"updatedAt": "2022-03-17T15:12:44+00:00",
"featured": false,
"aggregateReviewScore": null,
"productCategory": {
"id": 2,
"name": "Hex Set Screws",
"url": "hex-set-screws"
},
"productSubCategory": {
"id": 12,
"name": "Nylon",
"url": "nylon"
},
"images": [],
"productOptions": [
{
"id": 1,
"name": "Colour",
"productOptionItems": {
"0": {
"id": 2,
"name": "Black",
"productOptionItemValue": [
{
"id": 1196,
"stock": 1,
"price": "1.00",
"useOwn": false
},
{
"id": 1201,
"stock": 1,
"price": "1.00",
"useOwn": false
},
{
"id": 1198,
"stock": 1,
"price": "1.00",
"useOwn": false
}
]
},
"1": {
"id": 8,
"name": "Yellow",
"productOptionItemValue": [
{
"id": 1197,
"stock": 1,
"price": "1.00",
"useOwn": false
}
]
},
"2": {
"id": 14,
"name": "Light Grey"
},
"3": null,
"4": {
"id": 15,
"name": "Mid Grey"
},
"7": null,
"8": {
"id": 20,
"name": "Light Blue"
},
"11": null,
"12": {
"id": 22,
"name": "Purple"
},
"13": null
}
},
{
"id": 2,
"name": "Pack Size",
"productOptionItems": [
{
"id": 3,
"name": "10",
"productOptionItemValue": [
{
"id": 1180,
"stock": 100,
"price": "10.00",
"useOwn": true
}
]
},
{
"id": 4,
"name": "100",
"productOptionItemValue": [
{
"id": 1181,
"stock": 10,
"price": "1000.00",
"useOwn": true
}
]
}
]
}
],
"productSpecifications": []
}
If I run the same query on a SINGLE product (so the same Doctrine Query as a above just with a p.id = :id WHERE added) it returns absolutely fine. See the response for that below (and the CORRECT response I am looking for):
{
"id": 373,
"name": "test",
"code": "test",
"url": "373-test",
"price": 1,
"stock": 1,
"description": "<p>fghfgh mnsdbfksdhfjk sd</p>\n",
"live": false,
"createdAt": "2022-03-17T14:45:35+00:00",
"updatedAt": "2022-03-17T15:12:44+00:00",
"featured": false,
"aggregateReviewScore": null,
"productCategory": {
"id": 2,
"name": "Hex Set Screws",
"url": "hex-set-screws"
},
"productSubCategory": {
"id": 12,
"name": "Nylon",
"url": "nylon"
},
"images": [],
"productOptions": [
{
"id": 1,
"name": "Colour",
"productOptionItems": [
{
"id": 2,
"name": "Black",
"productOptionItemValue": {
"id": 1196,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 7,
"name": "Red",
"productOptionItemValue": {
"id": 1201,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 8,
"name": "Yellow",
"productOptionItemValue": {
"id": 1197,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 14,
"name": "Light Grey",
"productOptionItemValue": {
"id": 1202,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 15,
"name": "Mid Grey",
"productOptionItemValue": {
"id": 1205,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 20,
"name": "Light Blue",
"productOptionItemValue": {
"id": 1203,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 22,
"name": "Purple",
"productOptionItemValue": {
"id": 1204,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 23,
"name": "Natural",
"productOptionItemValue": {
"id": 1198,
"stock": 1,
"price": 1,
"useOwn": false
}
}
]
},
{
"id": 2,
"name": "Pack Size",
"productOptionItems": [
{
"id": 3,
"name": "10",
"productOptionItemValue": {
"id": 1180,
"stock": 100,
"price": 10,
"useOwn": true
}
},
{
"id": 4,
"name": "100",
"productOptionItemValue": {
"id": 1181,
"stock": 10,
"price": 1000,
"useOwn": true
}
}
]
}
],
"productSpecifications": []
}
Any help or ideas would be greatly appreciated!

Mysql search in json array with Like operator

I have a problem with MySQL json type. I want to search in mysql json array and get rows. My json data this
{
"id": 361,
"email": "example#outlook.com",
"code": null,
"username": null,
"permissions": null,
"created_at": "2019-03-01 16:09",
"updated_at": "2019-03-01 16:09",
"user_profile": {
"id": 361,
"name": "Jhon",
"surname": "Doe",
"father_name": "NED",
"birthday": "1994-12-15",
"fin_code": "6A56BS7",
"ssn": "AAA12830157",
"account_number": "account123",
"country": "USA",
"city": "NEW YORK",
"address": "EXample r",
"address_n": "Khani/Bina",
"mobile_phone": "(($717865643",
"phone": "0123456789",
"additional_email": "e.example#gmail.com",
"education": [
{
"endDate": "2020-06",
"startDate": "2015-09",
"profession": "Computer Since",
"university": "State University",
"educationType": 99
}
],
"language": [
{
"id": 102,
"level": 106
},
{
"id": 103,
"level": 106
},
{
"id": 104,
"level": 107
}
],
"computer_skills": [
{
"level": 106,
"skill": "php"
},
{
"level": 107,
"skill": "java"
}
],
"family_composition": [
{
"name": "Jhon",
"level": 126,
"surname": "Snow",
"birthday": "1992-02-08",
"fatherName": "Ned"
},
{
"name": "Jhon",
"level": 126,
"surname": "Snow",
"birthday": "1992-05-18",
"fatherName": "Ned"
}
],
"experience": [
{
"job": 128,
"time": 22,
"level": 8,
"salary": 2200,
"jobSign": 128,
"jobStatus": 267,
"startDate": "2012-12-12",
"orderNumber": "123dsa",
"jobSituation": 273,
"additionalSalary": 800
}
],
"reproach": [
{
"doc": 228,
"date": "2011-11-11",
"note": "Some reason",
"level": 225,
"number": "123dsa",
"reason": "islemir",
"article": 233
}
],
"additional_information": "All is work",
"citizen": {
"id": 5,
"name": "United States"
},
"cities": {
"id": 21,
"name": "New York"
},
"countries": {
"id": 89,
"name": "Unated States"
},
"gender": {
"id": 1,
"name": "Man"
},
"marital": {
"id": 4,
"name": "Single"
},
"work": {
"id": 269,
"name": "Able"
},
"party": {
"id": 10,
"name": "Digər"
},
"military": {
"id": 121,
"name": "OK"
},
"institution": null
}
}
I want to search like this:
WHERE education.'$[*].profession' Like %Computer%
But this syntax is not working. Thank you for replying. I developed my project in Laravel 5.7 if this is help for any suggestion. I don't use JSON_SEARCH() because this function returns the key but I need to return rows for my search query.
If you are on MySQL 5.7, this should work
.....WHERE JSON_EXTRACT(education , "$.profession") Like '%Computer%';
I found this solution and it worked for me:
UPPER(education->"$[*].profession") LIKE UPPER("% Computer %")
For Laravel syntax I write the PHP code like this:
$query=$query->whereRaw('UPPER(education->"$[*].profession") LIKE UPPER("%' . $profession . '%")');
Tested with MySQL 5.7:
SELECT 'found it!' FROM whatever_your_table_name_is
WHERE whatever_your_column_name_is->>'$.user_profile.education[*].profession'
LIKE '%Computer%';
Output, showing the WHERE clause matches the document:
+-----------+
| found it! |
+-----------+
| found it! |
+-----------+
As with most other questions about JSON in MySQL, I think you would be better off storing data in normalized tables.

Get all options for configurable product Magento 2.0 REST Api

When i call this API,
{{base_url}}index.php/rest/V1/configurable-products/:sku/options/all
I am getting a response like this,
[
{
"id": 9,
"attribute_id": "93",
"label": "Color",
"position": 0,
"values": [
{
"value_index": 15
},
{
"value_index": 16
},
{
"value_index": 17
}
],
"product_id": 19
},
{
"id": 10,
"attribute_id": "176",
"label": "side",
"position": 1,
"values": [
{
"value_index": 18
},
{
"value_index": 19
}
],
"product_id": 19
}
]
But i want label for all these value_indexes.Could i get all these values in a single request
There is an pi for getting all the labels,
{{base_url}}/index.php/rest/V1/products/attributes/:attribute_id/options
Ex:
{{base_url}}/index.php/rest/V1/products/attributes/93/options
will return
[
{
"label": " ",
"value": ""
},
{
"label": "green",
"value": "12"
},
{
"label": "yellow",
"value": "13"
},
{
"label": "red",
"value": "14"
}
]
You can use this endpoint to fetch multiple attribute sets in a single request
/rest/V1/products/attributes
example:
{domain}/rest/V1/products/attributes?search_criteria[filter_groups][0][filters][0][field]=attribute_id&search_criteria[filter_groups][0][filters][0][value]=93,138&search_criteria[filter_groups][0][filters][0][condition_type]=in
response:
"items": [
{
"is_wysiwyg_enabled": false,
"is_html_allowed_on_front": false,
"used_for_sort_by": false,
"is_filterable": true,
"is_filterable_in_search": false,
"is_used_in_grid": true,
"is_visible_in_grid": false,
"is_filterable_in_grid": true,
"position": 0,
"apply_to": [
"simple",
"virtual",
"configurable"
],
"is_searchable": "1",
"is_visible_in_advanced_search": "1",
"is_comparable": "1",
"is_used_for_promo_rules": "0",
"is_visible_on_front": "0",
"used_in_product_listing": "0",
"is_visible": true,
"scope": "global",
"attribute_id": 93,
"attribute_code": "color",
"frontend_input": "select",
"entity_type_id": "4",
"is_required": false,
"options": [
{
"label": " ",
"value": ""
},
{
"label": "blue",
"value": "8"
},
{
"label": "red",
"value": "9"
},
{
"label": "black",
"value": "10"
},
{
"label": "white",
"value": "11"
}
],
"is_user_defined": true,
"default_frontend_label": "Color",
"frontend_labels": [],
"backend_type": "int",
"source_model": "Magento\\Eav\\Model\\Entity\\Attribute\\Source\\Table",
"default_value": "",
"is_unique": "0",
"validation_rules": []
},
{
"is_wysiwyg_enabled": false,
"is_html_allowed_on_front": true,
"used_for_sort_by": false,
"is_filterable": false,
"is_filterable_in_search": false,
"is_used_in_grid": true,
"is_visible_in_grid": true,
"is_filterable_in_grid": true,
"position": 0,
"apply_to": [],
"is_searchable": "0",
"is_visible_in_advanced_search": "0",
"is_comparable": "0",
"is_used_for_promo_rules": "0",
"is_visible_on_front": "0",
"used_in_product_listing": "0",
"is_visible": true,
"scope": "global",
"attribute_id": 138,
"attribute_code": "simple_size",
"frontend_input": "select",
"entity_type_id": "4",
"is_required": true,
"options": [
{
"label": " ",
"value": ""
},
{
"label": "small",
"value": "12"
},
{
"label": "medium",
"value": "13"
},
{
"label": "large",
"value": "14"
}
],
"is_user_defined": true,
"default_frontend_label": "simple_size",
"frontend_labels": [
{
"store_id": 1,
"label": "Size"
}
],
"backend_type": "int",
"source_model": "Magento\\Eav\\Model\\Entity\\Attribute\\Source\\Table",
"default_value": "",
"is_unique": "0",
"validation_rules": []
}
],
"search_criteria": {
"filter_groups": [
{
"filters": [
{
"field": "attribute_id",
"value": "93,138",
"condition_type": "in"
}
]
}
]
},
"total_count": 2
}

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//2dZVJvH4D7WJvnJTtK5O4TWNrkiTmEdHp55yRmjwWfsgNswOIMXoWrZj3OUJ4DH4POJ8rmfilimvtpBCdxNsqoZDVC9d6/6LiICZ3wHZJ7w/88QuExFV7OsHbc+jI3trRzDCCb6Ns62MGyfsXX6Pz8mJe6gs02UjapVSPa3M9CqLGMCN0xCF28WNbavhSI9jG3cWsQbxGU8rnhmjx00Iw5v2qqjdE/Dx432Qzs4s36SqUjLF7KN9hAJoQuMX3emE4gZ+7ANJ5bDTDEYZlnUZ4iXKykzUptYDyGay0evu1kdCjxPJlgiEtOl3hFMaKC+eoTsjps4RoYy0Z7oD3aP52qCYPdCH+8XTic522UKU1mW9HMjmGxH5zrvYK2rOgzSR2+xH5K3IpXHBAQqWOTEvmirP4qvg5VOPjyO9mIM83I6aY1JAkqo9jYqtEwrGqANdhA9z78EdoyQYKZBXcLsQMKz06fAczwk/WxxIi1ctL8EW+aZYddkbPo7xD6NWc8bJ+ARw5AlS1tirVNcO3mN5jVr/a6qftVuaz/0q83VsX4ztQpgMjDkptbw9Zz6DNLgiLJEzdf7fraoVUyzeth5wucOMzpLBP+ERbD7XFnDSKN8QzG6lLpDK8qy95K5FMmcF4uDq8Y1waTyIN9sS+v50OTbjr7Ebs3uKIxMZFfGUfp7YpDiVyo+2x4La4K7rhHPtoR6iEfVCjnTAUvamQu3qgL3vuSCPPPJiHFbdOrKVlp3kfAxaIcJpX3Z+Twx2cNAhsGHSk2ZazzvP5Pw1EF066VcoDkld9Oe/Qu5cC+DtG2LHhMA7NU8hMD66q9UCsXC6P/mjbKr7hatjHyyklDIKuxxirMpYkukEa73RJlhKmC0fjj4EYcgRy5MtybexuN59KaTeSEFxMGFIkv0zHp5jO/wHUvyypqbxTKFR3VAx6WpmSNg/Iui2uXDhNu/F4zJnYQUW9EyluZEPebFk2Uj455O2+y0UmFe4WnUY+0d92obZNv855/ctA4UC/LQn2s9azqdhDIeUUHuHEn2a4Grb+7l8wuai6ybBmmE62ck+CqMou+A+CUwk71KMkh3ZXf8BdeelW8Ia7r9ja7wKNBklgYo4Q8xOR63QhyCt2BiiR9aOxiDIKiW7bxSFCBga7yIPWx/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);

Get information from multidimensional json in php

I am trying to get back information from a multidimensional json array but can't seem to get it right.
Below is an example of the output from the url which you can see yourself at http://109.255.189.130:3000/
{ "vnc_version": "2.1.0.0", "mod_version": "1.0.0.0", "server": { "name": "Pure Blood", "framework": "Microsoft Windows NT 6.2.9200.0" }, "stats": { "uptime": 53462.0, "uptime_peak": 53462.0, "online": 1, "online_max": 1, "online_peak": 2, "unique": 1, "unique_max": 1, "unique_peak": 2, "items": 111752, "items_max": 112259, "items_peak": 112259, "mobiles": 37963, "mobiles_max": 37976, "mobiles_peak": 37978, "guilds": 0, "guilds_max": null, "guilds_peak": 0 }, "players": [ { "info": { "id": 1, "name": "aN.Droid", "title": "", "profile": "", "guild_id": -1, "guild_abbr": "" }, "stats": [ ], "skills": [ ], "equip": [ ] } ], "guilds": [ ] }
What I would like to do is echo the name in the players array. There will be more than one player.
Can anyone please help me out here and point me in the correct direction to get this information?
I am very new to json so excuse my ignorance on the subject.
Thank you!
<?php
$json = '{ "vnc_version": "2.1.0.0", "mod_version": "1.0.0.0", "server": { "name": "Pure Blood", "framework": "Microsoft Windows NT 6.2.9200.0" }, "stats": { "uptime": 54383.3, "uptime_peak": 54383.3, "online": 1, "online_max": 1, "online_peak": 2, "unique": 1, "unique_max": 1, "unique_peak": 2, "items": 111672, "items_max": 112259, "items_peak": 112259, "mobiles": 37944, "mobiles_max": 37976, "mobiles_peak": 37978, "guilds": 0, "guilds_max": null, "guilds_peak": 0 }, "players": [ { "info": { "id": 1, "name": "aN.Droid", "title": "", "profile": "", "guild_id": -1, "guild_abbr": "" }, "stats": [ ], "skills": [ ], "equip": [ ] } ], "guilds": [ ] }';
$array = json_decode($json, true);
// you want 'true' as the second parameter so it tunrs this JSON data into a multidimensional array instead of objects.
foreach($array['players'] as $player){
print_r($player['info']);
//etc.. do what you want with each player
}
$json = '{ "vnc_version": "2.1.0.0", "mod_version": "1.0.0.0", "server": { "name": "Pure Blood", "framework": "Microsoft Windows NT 6.2.9200.0" }, "stats": { "uptime": 53462.0, "uptime_peak": 53462.0, "online": 1, "online_max": 1, "online_peak": 2, "unique": 1, "unique_max": 1, "unique_peak": 2, "items": 111752, "items_max": 112259, "items_peak": 112259, "mobiles": 37963, "mobiles_max": 37976, "mobiles_peak": 37978, "guilds": 0, "guilds_max": null, "guilds_peak": 0 }, "players": [ { "info": { "id": 1, "name": "aN.Droid", "title": "", "profile": "", "guild_id": -1, "guild_abbr": "" }, "stats": [ ], "skills": [ ], "equip": [ ] } ], "guilds": [ ] }';
$arr = json_decode($json, true);
foreach($arr["players"] as $player) print($player["info"]["name"]."<br/>");

Categories