This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
We'll use our collection to create a shopping list that combines all recipe ingredients.
NOTE in_array vs array_key_exists
in_array
will check the "value" in an array while array_key_exists
will check the "key" in an array.
Code Sample
This code will NOT handle all plural vs singular ingredients, but this will get you started. You could be adding "es" or changing "y" to "ies".
public function getCombinedIngredients()
{
$ingredients = array();
foreach ($this->recipes as $recipe) {
foreach ($recipe->getIngredients() as $i) {
$item = $i['item'];
if (strpos($item, ",")) {
$item = strstr($item, ",", true);
}
if (array_key_exists($item . "s", $ingredients)) {
$item .= "s";
} else if (array_key_exists(substr($item,0,-1),$ingredients)) {
$item = substr($ingredient,0,-1);
}
$ingredients[$item][] = array($i["amount"],$i["measure"]);
}
}
return $ingredients;
}
Documentation
Challenge
Setup calculations to return the amount of each item.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up