I'm working on a filter system to filter out food items being displayed on a menu. Every document in the menu collection contains the name of the category (or course if you will) and an array of food items.
I've tried various solutions such as the following code which gets me closer to the desired output.
foreach($menu as $category){
foreach($category["fooditems"] as $fooditem){
if ($fooditem["vegetarian"] == false){
if (($key = array_search($fooditem, (array) $category["fooditems"])) !== false)
unset($category["fooditems"][$key]);
}
}
}
Before:
{
"category" : "Starters",
"fooditems" : [
{
"name" : "No meat",
"vegetarian" : true,
},
{
"name" : "Horse Meat",
"vegetarian" : false,
},
{
"name" : "Some more meat",
"vegetarian" : false,
}
]
}
Expected after:
{
"category" : "Starters",
"fooditems" : [
{
"name" : "No meat",
"vegetarian" : true,
}
]
}
Actual after:
{
"category" : "Starters",
"fooditems" : [
{
"name" : "No meat",
"vegetarian" : true,
},
{
"name" : "Some more meat",
"vegetarian" : false,
}
]
}
The problem is after it spots a non-vegetarian food item and unsets it, it stops looping. I have no idea why this occurs.
Thank you to anyone who answers :)