Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Sometimes we only want SOME of the objects in the collection. Enter filters. This is another piece of functionality or method to add to our collection class.
Array Functions
There are more advanced array functions that we could use to filter our array as well.
Array Map
Example:
$titles = array_map(
function ($recipe) {
return $recipe->getTitle();
},
$this->recipes
);
Array Filter
Example
$taggedRecipes = array_filter(
$this->recipes,
function ($recipes) use ($tag) {
return in_array(ucwords($tag),$recipes->getTagArray());
}
);
-
0:00
Okay, we're starting to get somewhere.
-
0:02
Now I want to be able to pull only the recipes with a particular tag.
-
0:07
Let's go back to our recipe collection.
-
0:15
We'll create a new method called filterByTag.
-
0:25
We'll pass in the value of the tag that we want to look for.
-
0:30
We'll initialize a new taggedRecipes array.
-
0:40
Then we can loop through the recipes and look for our tag.
-
0:55
We can use if in_array, we're going to make sure that our tag is lowercase.
-
1:02
We use strtolower.
-
1:06
And our tag.
-
1:09
Then we'll be looking in the recipe getTags.
-
1:17
If we find the tag, we'll add this recipe to our taggedRecipes.
-
1:33
Finally, we'll return our taggedRecipes.
-
1:39
Let's go back to our cookbook and use our new filter.
-
1:45
I'm going to create a new recipe collection.
-
1:48
This is going to be for any recipe tagged breakfast.
-
2:08
Then we can loop through the breakfast recipes after we filter by tag.
-
2:15
Here's our filter.
-
2:20
And we pass it breakfast.
-
2:24
Then we'll return each of these as recipe.
-
2:31
Then we're going to add this recipe to our breakfast collection.
-
2:43
Now let's render our breakfast recipes instead.
-
2:55
Now we see just the recipes that were tagged as breakfast.
-
2:59
There's one more feature that I'd like to see for our collection.
-
3:02
A shopping list.
-
3:03
We'll dive into that in the next video.
You need to sign up for Treehouse in order to download course files.
Sign up