Related
I am using the serializer component from Symfony.
https://symfony.com/doc/current/components/serializer.html
I want to convert the following response to a php class object.
{
"data": {
"uuid": "d1830cc0-f35a-11e8-8ca1-5254003b69f1",
"name": "***",
"last_name": "Admin",
"fullname": "***",
"email": "***#***.com",
"created_at": {
"time24": "16:13",
"time": "04:13",
"date": "2018-11-28",
"datetime": "2018-11-28 16:13:22",
"meta": {
"meridiem": "pm",
"day": 28,
"month": 11,
"year": 2018,
"month_name": "November"
}
},
"updated_at": {
"time24": "16:13",
"time": "04:13",
"date": "2018-11-28",
"datetime": "2018-11-28 16:13:22",
"meta": {
"meridiem": "pm",
"day": 28,
"month": 11,
"year": 2018,
"month_name": "November"
}
},
"relationships": {
"role": {
"uuid": "d14ee40e-f35a-11e8-bbfc-5254003b69f1",
"name": "admin",
"label": "Admin",
"public": true,
"created_at": {
"time24": "16:13",
"time": "04:13",
"date": "2018-11-28",
"datetime": "2018-11-28 16:13:21",
"meta": {
"meridiem": "pm",
"day": 28,
"month": 11,
"year": 2018,
"month_name": "November"
}
},
"updated_at": {
"time24": "16:13",
"time": "04:13",
"date": "2018-11-28",
"datetime": "2018-11-28 16:13:21",
"meta": {
"meridiem": "pm",
"day": 28,
"month": 11,
"year": 2018,
"month_name": "November"
}
},
"relationships": {
"permissions": [
{
"name": "admin",
"label": "Admin"
}
]
}
}
}
}
}
What I was trying to do is to use this website:
https://jacobdekeizer.github.io/json-to-php-generator/#/
It gave me a long series of classes, to summarize, the root object looks like this:
class Response
{
public Data $data;
public function getData(): Data
{
return $this->data;
}
public function setData(Data $data): self
{
$this->data = $data;
return $this;
}
}
Then I'm trying to deserialize it like this:
/** #var Response $response */
$response = $this->serializer->deserialize($response->getContent(), Response::class, 'json');
But I'm getting the following error:
Failed to denormalize attribute "data" value for class "App\Http\Booking\Models\Response": Expected argument of type "App\Http\Booking\Models\Data", "array" given at property path "data".
My serialize object looks like this:
class MySerializer {
public static function getSerializer()
{
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer(), new ArrayDenormalizer()];
return new Serializer($normalizers, $encoders);
}
}
Been struggling with this for too long now, so am kindly asking for your help.
How can I, using PHP, get the values of the text fields in the reviews of which there are three in this JSON file below.
Want to use a foreach loop for this, thanks for helping me out!
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
],
You can use this code
<?php
$json = <<<EOF
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
]
}
EOF;
$array = json_decode($json, true);
$texts = array_map(
function($item) {
return $item['text'];
}, $array['reviews']
);
It doesn't seem like you need a foreach to fetch the reviews element. Not sure if I understood your question correct, but did you want something like this:
$assoc_json = json_decode($your_json, true);
var_dump($assoc_json['reviews']);
The above turns your json into an associative array, and just access the review element.
A simple, naive approach would be:
//Loads your json file 'tripadvisor' into jsonString
$jsonString = file_get_contents("/tripadvisor.json");
//Turns your string into an associative array
$tripJsonAssoc = json_decode($jsonString, true);
//Iterate through each review and store it in result
$result = array();
foreach($tripJsonAssoc['reviews'] as $review) {
$result[] = array('text' => $review['text'],
'rating' => $review['rating']);
}
//Do what you need to do with result
//...
Or you can just do your own stuff inside the foreach loop.
This answer gives you another way (more elegant) to create the 'result' array, but since you asked for a 'foreach', I thought I would add my 5 cents.
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;
}
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);
I have this JSON code:
{
"phrases": [
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa\r\n",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
}
],
"details": {
"success": "true",
"phrase_id": "",
"phrase_text": "",
"phrase_date": ""
}
}
I don't really know what to do. I get some phrases vía MySQL, and pushes them to an array. This array is json_encoded() and gets printed.
$sth = $sql;
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$sth = $sql;
$data = array(
"success" => "true",
"phrase_id" => "",
"phrase_text" => "",
"phrase_date" => "",
);
print json_encode($rows).json_encode($data);
and with jQuery I was trying to parse it, but I can't. This is the main problem.
function getPhrases(order,limit,last){
var req_url = ...;
$.getJSON(req_url, function(data) {
$.each(data.phrases, function(i, data) {
appendPhrase(data.text);
lastid = data.id;
});
$.each(data.details, function(i, data) {
$("#phrases-count").html(data.totalcount);
});
});
}
PS: I was doing this with "echo" but got some problems.
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa<br />",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
}
],
"details": [
{
"totalcount": "3",
"logged_in": "false"
}
]
}
You can't simply combine these JSON arrays:
print json_encode($rows).json_encode($data);
Try this (attempt 2):
print json_encode( array('phrases' => $rows, 'details' => $data) );