I have a application running on ALEXA (Amazon Echo). I'm implementing Home card display with images. When for a particular call if the response has only one card. It shows perfectly fine. Screenshot attached
"Response": {
"version" : "1.0",
"sessionAttributes": {
"UserCityId": "1",
"UserCity": "London",
"latitude": "51.50735090",
"longitude": "-0.12775830",
"categoryID": "900",
"company_id": "1154916",
"first_name": "User FName",
"yes_no_for": "",
"cat_start_limit": "0",
"categoryName": "music",
"total_cat_events": "2178",
"show_rec": "5"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "This is what alexa speaks out"
},
"card": {
"type": "Standard",
"title": "Music events in London",
"text": "The speech passed to alexa",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know events for music ,sports, or something else. Please select one category"
}
},
"shouldEndSession": false
}
}
The above code works
The problem is listed below :
But if the same response has array of cards (multiple cards), alexa fails giving an error.
"Response": {
"version": "1.0",
"sessionAttributes": {
"UserCityId": "1",
"UserCity": "London",
"latitude": "51.50735090",
"longitude": "-0.12775830",
"categoryID": "900",
"customer_id": "1154916",
"first_name": "UserFNAME",
"yes_no_for": "",
"cat_start_limit": "0",
"categoryName": "music",
"total_cat_events": "2178",
"show_rec": "5"
},
"response" : {
"outputSpeech" : {
"type": "PlainText",
"text": "5th. Baba Yaga's Hut Presents Jambinai, at Corsica Studios, on Monday, May 16th , 7 30 pm"
},
"card": [{
"type": "Standard",
"title": "Music events in London",
"text": "1. Dove Jones Blues Jam!, at Phoenix Artist Club, on Monday, May 16th , 7pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}, {
"type": "Standard",
"title": "Music events in London",
"text": "2. The Hillbilly Moon Explosion, at The Borderline, on Monday, May 16th, 7pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}, {
"type": "Standard",
"title": "Music events in London",
"text": "3. Sian Evans Of Kosheen, at 100 Club, on Monday, May 16th , 7 30 pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}, {
"type": "Standard",
"title": "Music events in London",
"text": "4. Rinocerose, at The Water Rats, on Monday, May 16th , 7 30 pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}, {
"type": "Standard",
"title": "Music events in London",
"text": "5. Baba Yaga's Hut Presents Jambinai, at Corsica Studios, on Monday, May 16th , 7 30 pm",
"image": {
"smallImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg",
"largeImageUrl": "https:\/\/xyz.com\/version\/sports-car-1374425_960_720.jpg"
}
}],
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know events for music ,sports, or something else. Please select one category"
}
},
"shouldEndSession" : false
}
}
The above code doesn't work.
Here is the thing that I'm trying to convert : Please see the screenshot
For events in london call I get list of 5 events in single card. To each event I want to assign image and create its card.
Can anyone help with the approach and figure out what is the problem using multiple card in JSON response.
Is it that alexa only support single card in response ?
The card attribute on the response takes an object not an array.
Here is the example that Amazon uses on their site:
{
"version": "string",
"sessionAttributes": {
"string": object
},
"response": {
"outputSpeech": {
"type": "string",
"text": "string",
"ssml": "string"
},
"card": {
"type": "string",
"title": "string",
"content": "string",
"text": "string",
"image": {
"smallImageUrl": "string",
"largeImageUrl": "string"
}
},
"reprompt": {
"outputSpeech": {
"type": "string",
"text": "string",
"ssml": "string"
}
},
"shouldEndSession": boolean
}
}
If you wanted to try and make multiple cards, you could try sending multiple responses, but I am not sure that that would work either.
I think your best option is to consider a different interaction with the user for your problem then presenting multiple cards.
Related
I try to implement paypal express checkout in a way that users are able to manipulate their order after they logged in with Paypal and when they are done, click "bux now" and the actual payment is capured.
To do so, I created the order with paypal before with intend "Authorize". The user logs into paypal and comes back to my shop to manage the order. When done, I want to use paypals updateOrder Call to apply the users changes. But It always bounces with error REFERENCE_ID_NOT_FOUND.
Here is the documentation:
https://developer.paypal.com/api/orders/v2/#orders_patch
Here is, what I send to Paypal.
[{
"op": "replace",
"path": "\/purchase_units\/#reference_id=='default'",
"value": [{
"reference_id": "2295037",
"description": "Your order at Shop",
"custom_id": "Shop Id 2295037",
"soft_descriptor": "Shopname",
"invoice_id": "2295037",
"amount": {
"currency_code": "EUR",
"value": 59.98,
"breakdown": {
"item_total": {
"currency_code": "EUR",
"value": 50.4
},
"shipping": {
"currency_code": "EUR",
"value": 0
},
"discount": {
"currency_code": "EUR",
"value": 0
},
"tax_total": {
"currency_code": "EUR",
"value": 9.58
}
}
},
"items": [{
"name": "Product 1",
"description": "Product Descr. 1",
"sku": "1019879",
"unit_amount": {
"currency_code": "EUR",
"value": 16.8
},
"tax": {
"currency_code": "EUR",
"value": 3.19
},
"quantity": "1",
"category": "PHYSICAL_GOODS"
}, {
"name": "Product 2",
"description": "Product Descr. 2",
"sku": "1024593",
"unit_amount": {
"currency_code": "EUR",
"value": 33.61
},
"tax": {
"currency_code": "EUR",
"value": 6.38
},
"quantity": "1",
"category": "PHYSICAL_GOODS"
}],
"shipping": {
"name": {
"full_name": "John Doe"
},
"address": {
"address_line_1": "Badensche Str. 24",
"address_line_2": "",
"admin_area_2": "Berlin",
"postal_code": "10715",
"country_code": "DE"
}
}
}]
}]
The answer from Paypal is "REFERENCE_ID_NOT_FOUND". Paypal itself suggests 'default' if there is only one purchase unit (which it is). I also tried to replace 'default' with the reference_id in our system (which was provided with the createOrder call) or paypal´s own transactionId (which is provided through the endpoint anyway). The error is always the same.
How can I change this call so that Paypal accepts it and updates the order in its system?
It turned out, that I had a mistake by sending the value as an array insterad of an object. With the shops own reference Id it worked after fixing this issue.
The Error code-Reposne by paypal was misleading:
"value": [{
->
"value": {
I have been on a little project of mine now i want to find imdb_id using tmdb_id so for that I have been trying to use the API.
https://api.themoviedb.org/3/tv/67026?api_key=myapikey&append_to_response=external_ids
which brings up the results like this
{
"backdrop_path": "/hcFbIbDzsB9aSSw9VkSGFEl5sGO.jpg",
"created_by": [{
"id": 230174,
"credit_id": "577eb8e5c3a368694a0027ac",
"name": "David Guggenheim",
"gender": 2,
"profile_path": "/hqSydaadHO6EsBIn3BQEzzfxNUY.jpg"
}],
"episode_run_time": [42],
"first_air_date": "2016-09-21",
"genres": [{
"id": 18,
"name": "Drama"
}, {
"id": 10768,
"name": "War & Politics"
}],
"homepage": "https://www.netflix.com/title/80113647",
"id": 67026,
"in_production": false,
"languages": ["en"],
"last_air_date": "2019-06-07",
"last_episode_to_air": {
"air_date": "2019-06-07",
"episode_number": 10,
"id": 1809432,
"name": "#truthorconsequences",
"overview": "On election day, Kirkman turns to his therapist to assuage his conscience about the events -- and his own decisions -- of the momentous prior 36 hours.",
"production_code": "",
"season_number": 3,
"show_id": 67026,
"still_path": "/cpy3uV100RyZuvJN535JLTrj4Nz.jpg",
"vote_average": 7.0,
"vote_count": 1
},
"name": "Designated Survivor",
"next_episode_to_air": null,
"networks": [{
"name": "ABC",
"id": 2,
"logo_path": "/ndAvF4JLsliGreX87jAc9GdjmJY.png",
"origin_country": "US"
}, {
"name": "Netflix",
"id": 213,
"logo_path": "/wwemzKWzjKYJFfCeiB57q3r4Bcm.png",
"origin_country": ""
}],
"number_of_episodes": 53,
"number_of_seasons": 3,
"origin_country": ["US"],
"original_language": "en",
"original_name": "Designated Survivor",
"overview": "Tom Kirkman, a low-level cabinet member is suddenly appointed President of the United States after a catastrophic attack during the State of the Union kills everyone above him in the Presidential line of succession.",
"popularity": 30.031,
"poster_path": "/5R125JAIh1N38pzHp2dRsBpOVNY.jpg",
"production_companies": [{
"id": 28788,
"logo_path": null,
"name": "Genre Films",
"origin_country": "US"
}, {
"id": 19366,
"logo_path": "/vOH8dyQhLK01pg5fYkgiS31jlFm.png",
"name": "ABC Studios",
"origin_country": "US"
}, {
"id": 78984,
"logo_path": null,
"name": "Entertainment 360",
"origin_country": "US"
}],
"seasons": [{
"air_date": "2016-09-20",
"episode_count": 21,
"id": 78328,
"name": "Season 1",
"overview": "Tom Kirkman, a low-level cabinet member is suddenly appointed President of the United States after a catastrophic attack during the State of the Union kills everyone above him in the Presidential line of succession.",
"poster_path": "/1QHlD6z9FnXuuTDVLJnjrtLfVyq.jpg",
"season_number": 1
}, {
"air_date": "2017-09-27",
"episode_count": 22,
"id": 91130,
"name": "Season 2",
"overview": "",
"poster_path": "/z4hdj8cYyqCO9lVBOGm6YZsnMho.jpg",
"season_number": 2
}, {
"air_date": "2019-06-07",
"episode_count": 10,
"id": 122914,
"name": "Season 3",
"overview": "",
"poster_path": "/wn310FWQhjjpHbqsMRBcXr28EHc.jpg",
"season_number": 3
}],
"status": "Canceled",
"type": "Scripted",
"vote_average": 7.2,
"vote_count": 408,
"external_ids": {
"imdb_id": "tt5296406",
"freebase_mid": null,
"freebase_id": null,
"tvdb_id": 311876,
"tvrage_id": 51115,
"facebook_id": "DesignatedSurvivor",
"instagram_id": "designatedsurvivor",
"twitter_id": "DesignatedNFLX"
}
}
So now if I want to get just the IMDb_ID form the external_ids then what code should i use in PHP and store it in a variable.
Thank you very much in advance.
use the json_decode method to treat JSON like a PHP object
$data = 'your JSON object';//raw data as string in $data
$decoded = json_decode($data);//decoded data as PHP object
echo $decoded->external_ids->imdb_id; //access any property you like
hope this helps!!!
I think I'm over looking something incredibly simple here.
When I create a new billing agreement through the PayPal PHP SDK I'm returned to my store by the following URL..
/paypal-success?success=true&token=EC-3K353628LH3197445
I have created a WebHook for the Subscription Created event that posts JSON as follows
{
"id": "WH-5UR49681MC703253M-3S161814MB664705V",
"event_version": "1.0",
"create_time": "2018-03-17T17:21:47.120Z",
"resource_type": "Agreement",
"event_type": "BILLING.SUBSCRIPTION.CREATED",
"summary": "A billing subscription was created",
"resource": {
"agreement_details": {
"outstanding_balance": {
"value": "0.00"
},
"num_cycles_remaining": "0",
"num_cycles_completed": "0",
"next_billing_date": "2018-03-17T10:00:00Z",
"last_payment_date": "2018-03-17T17:21:44Z",
"last_payment_amount": {
"value": "1.00"
},
"final_payment_due_date": "1970-01-01T00:00:00Z",
"failed_payment_count": "0"
},
"description": "x",
"links": [{
"href": "api.sandbox.paypal.com/v1/payments/billing-agreements/I-55KA5N9GPPJW",
"rel": "self",
"method": "GET"
}],
"shipping_address": {
"recipient_name": "test buyer",
"line1": "Spitalfields Arts Market, 112 Brick Lane,",
"city": "London",
"state": "London",
"postal_code": "E1 6RL",
"country_code": "GB"
},
"id": "I-55KA5N9GPPJW",
"state": "Active",
"payer": {
"payment_method": "paypal",
"status": "verified",
"payer_info": {
"email": "jamie-buyer#x.com",
"first_name": "test",
"last_name": "buyer",
"payer_id": "Q3TZFN4F7NHJ6",
"shipping_address": {
"recipient_name": "test buyer",
"line1": "Spitalfields Arts Market, 112 Brick Lane,",
"city": "London",
"state": "London",
"postal_code": "E1 6RL",
"country_code": "GB"
}
}
},
"plan": {
"curr_code": "USD",
"links": [],
"payment_definitions": [{
"type": "REGULAR",
"frequency": "Month",
"frequency_interval": "1",
"amount": {
"value": "49.99"
},
"cycles": "0",
"charge_models": [{
"type": "TAX",
"amount": {
"value": "0.00"
}
},
{
"type": "SHIPPING",
"amount": {
"value": "0.00"
}
}]
}],
"merchant_preferences": {
"setup_fee": {
"value": "1.00"
},
"auto_bill_amount": "YES",
"max_fail_attempts": "0"
}
},
"start_date": "2018-03-17T00:00:00Z"
},
"links": [{
"href": "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-5UR49681MC703253M-3S161814MB664705V",
"rel": "self",
"method": "GET"
},
{
"href": "https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-5UR49681MC703253M-3S161814MB664705V/resend",
"rel": "resend",
"method": "POST"
}]
}
That token generated when the user is redirected back to my store does not appear to be in the WebHooks JSON.
How do you link your PayPal users once they are redirected back to your store to the incoming WebHooks?
The token returned in your success url is used to activate the agreement after the user accepts the agreement on PayPal. Once you activate the agreement you can retrieve the agreement id. That id is in your web hook under resources/id. "id": "I-55KA5N9GPPJW". There may be a better way to deal with this but I created a subscription table that associates the agreement id to the user id and a transactions table that has the agreement id and the associated webhook information.
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 am trying to set up a form to allow users to update data in a large JSON file. I have a form that allows the user to grab the 'event' they want and to edit it. When they click submit, it sends the data to a script that pulls the entire JSON file into an array. From there, I need the script to search through that array and find the index of the sub-array that has the same ID as the 'event' that has been edited. So if the user has edited the entry called "William Bradford born", I need the script to match the ID "american-ccincore-1411541230" and return 0 for that sub-array's index.
[
{
"id" : "american",
"title" : "A Timeline of American Literature",
"description" : "LENGTHY DESCRIPTIVE TEXT",
"initial_zoom" : "50",
"focus_date" : "1650-01-01 00:00:00",
"size_importance" : "true",
"timezone" : "-06:00",
"min_zoom" : "20",
"max_zoom" : "80",
"image_lane_height" : "50",
"display_zoom_level" : "1",
"tags" : {
"Puritan" : "0",
"Enlightenment" : "0",
"Romantic" : "0",
"Transcendental" : "0",
"Dark Romantic": "0",
"African American": "0",
"American Indian": "0",
"International" : "0"
},
"legend": [
{
"title": "Author event",
"icon": "star_red.png"
},
{
"title": "Publication event",
"icon": "square_blue.png"
},
{
"title": "Historical event",
"icon": "triangle_green.png"
}
],
"events": [
{
"id": "american-ccincore-1411541230",
"title": "William Bradford born",
"description": "LENGTHY DESCRIPTIVE TEXT",
"tags": "Puritan",
"startdate": "1950-03- 00:00:00",
"enddate": "1657-05- 00:00:00",
"importance": "50",
"date_display": "year",
"link": "",
"image": "https://www.csustan.edu/sites/default/files/ENGLISH/reuben/pal/chap1/bradford.gif",
"icon": "star_red.png",
"span_color": "#f66"
}, {
"id": "american-mforkner-1411364607",
"title": "Church Mission Society",
"description": "LENGTHY DESCRIPTIVE TEXT",
"tags": "",
"startdate": "1799-01-01 00:00:00",
"enddate": "1799-01-01 00:00:00",
"importance": "50",
"date_display": "year",
"link": "",
"image": "http://webarchive.cms-uk.org/_images/tnsaies1.jpg",
"icon": ".png",
"span_color": "#ccc"
}
]
}
]
I've tried to adapt scripts suggested in a dozen or so posts here, but I can't get any to work in this particular situation. Thanks for any advice.
It's just a simple loop. The caveat is you need to distinguish between an answer of 0 and a failure to find the event you were looking for. I typically use false to indicate failure, but that means using === or !== for your comparison later.
function findEventIndexById($events, $target) {
$retval = false;
foreach($events as $index=>$oneEvent) {
if ($oneEvent->id == $target) {
$retval = $index;
break;
}
}
return $retval;
}
$foundIndex = findEventIndexById($data->events, $eventId);
if ($foundIndex !== false) {
// ... do stuff here to $data->events[$foundIndex]
} else
// ... report an error ...