PHP: Find index of array in multidimentional array based on given value - php

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 ...

Related

Why is PDO fetchAll() returning me same results twice?

I'm building a simple search engine in PHP with PDO. Everything works but fetchAll(PDO::FETCH_ASSOC) is returning me same results twice.
Here is my PHP code :
(Updated to display the id column...)
header('Content-Type: application/json');
$q = db()->prepare("SELECT id, title, description, type, mediaId FROM projects WHERE title LIKE ?");
$q->execute(array('%'.$search.'%'));
$d = $q->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($d);
Here are the results I get from PDO
[
{
"id" : "1",
"title": "PhonArt",
"description": "Games",
"type": "",
"mediaId": "linkA"
},
{
"id" : "1",
"title": "PhonArt",
"description": "Games",
"type": "",
"mediaId": "linkA"
},
{
"id" : "2",
"title": "BioState",
"description": "Biology",
"type": "",
"mediaId": "linkB"
},
{
"id" : "3",
"title": "SnaPhones Inc.",
"description": "A social network",
"type": "",
"mediaId": "linkC"
},
{
"id" : "2",
"title": "BioState",
"description": "Biology",
"type": "",
"mediaId": "linkB"
},
{
"id" : "3",
"title": "SnaPhones Inc.",
"description": "A social network",
"type": "",
"mediaId": "linkC"
}
]

Having trouble displaying Multiple Home Card Display on Alexa in Single Response

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.

PHP loop through data from JSON string

I want to get ItemCategory->id's for each Item->id
How can I do it in the best way?
Here is a part of JSON data item
"6": {
"Item": {
"id": "6",
"name": "test",
"description": "description",
},
"ItemThumbnail": null,
"ItemCategory": {
"3": {
"id": "3",
"name": "name",
"status": "active",
"date_created": "2015-07-07 11:23:52",
"date_updated": "0000-00-00 00:00:00",
},
"4": {
"id": "4",
"name": "name",
"status": "active",
"date_created": "2015-07-07 11:23:52",
"date_updated": "0000-00-00 00:00:00",
}
},
"ItemGroup": []
},
You can convert your json string to a PHP array using $array = json_decode($str, true);, then loop your array and extract the information you need.
See http://php.net/manual/en/function.json-decode.php for more detail on json_decode
After json decode use this.
foreach($Item as $Items)
{
$ItemCategory = $Items->ItemCategory;
foreach($ItemCategory as $ItemCategorys)
{
echo $ItemCategorys->id;
}
}

remove unnecessary hierarchy from json output

I am building an admin backend for an android app. My code provides a json output which the android developer then uses in his app. The developer asked me if it is possible to reduce the hierarchy level in the json output
as in remove the highlighted []0 and put the contents directly inside the []data instead.
This is my current php code
if($type == 1 ) //Handle item display
{
try
{
$query = "SELECT category FROM category";
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($row1 = $value->fetchAll(PDO::FETCH_OBJ)){
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
$result->closeCursor(); //Close database connection free resources
$DBH = null;
}
catch(PDOException $e){
print $e->getMessage ();
die();
}
}
And the json output being generated
[
{
"data": [
[
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
]
},
{
"data": {
"catagory": "Dinner"
}
},
{
"data": {
"catagory": "Soup"
}
},
{
"data": {
"catagory": "Test"
}
}
]
I am not very sure if I can make the changes he asked or if it is possible. Is it doable?
Your json structure is inconsistent and try this approach, will be easier for the developer to parse
{
"response": [
{
"data": [
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
},
{
"data": [
{
"catagory": "Dinner"
}
]
},
{
"data": [
{
"catagory": "Soup"
}
]
},
{
"data": [
{
"catagory": "Test"
}
]
}
]
}

PHP getting values from nested json

I have this json listed below. I was using json_decode to get some of the values. Such as getting the id value:
$decoded_array = json_decode($result, true);
foreach($decoded_array['issue'] as $issues ){
$value[] = $issues["id"];
This method is working for getting the id value, however, I want to get the emailAddress values for both Bob and John. I believe you can get a single value by doing this:
$value[] = $issues["fields"][people][0][emailAddress];
Is it possible to get both email addresses in an efficient manner?
Edited --------
How would you get data with an expanded dataset? Example:
{
"startAt": 0,
"issue": [
{
"id": "51526",
"fields": {
"people": [
{
"name": "bob",
"emailAddress": "bob#gmail.com",
"displayName": "Bob Smith",
},
{
"name": "john",
"emailAddress": "john#gmail.com",
"displayName": "John Smith",
}
],
"skill": {
"name": "artist",
"id": "1"
}
}
},
{
"id": "2005",
"fields": {
"people": [
{
"name": "jake",
"emailAddress": "jake#gmail.com",
"displayName": "Jake Smith",
},
{
"name": "frank",
"emailAddress": "frank#gmail.com",
"displayName": "Frank Smith",
}
],
"skill": {
"name": "writer",
"id": "2"
}
}
}
]
}
I only want to extract the email addresses from both "fields". Is there an easy way to loop through all the "fields" to get "emailAddress" data?
You need to delve deeper into the array.
foreach ($decoded_array['issue'][0]['fields']['people'] as $person) {
echo $person['emailAddress'];
}

Categories