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
In this video we’ll modify our function to show either the entire catalog or a specific category.
To display only the category items, we're going to create a function to return the keys of items in that category. This will work much the same way as array_rand worked by returning and array of 4 random keys.
Step 1: Create the Function
The function needs to accept the catalog of data, and the category to use. It will then return an array of keys.
inc/functions.php
function array_category($catalog,$category) {
$output = array();
return $output;
}
Step 2: Check the Catalog for the Category
Now we need to loop through the items and compare the item category to the passed in category. We need the ID since we're going to return an array of ID's. If we DO NOT want case to matter when comparing these categories, we can use the strtolower() function.
inc/functions.php
foreach ($catalog as $id => $item) {
if (strtolower($category) == strtolower($item["category"])) {
$output[] = $id;
}
}
Step 3: Call the Function and Display the Items
This is going to work in the same way as our utilization of array_rand. We'll pass the $catalog data, and the $selection which represents our category. Then we loop through the returned array and display the item html.
catalog.php
$categories = array_category($catalog,$section);
foreach ($categories as $id) {
echo get_item_html($id,$catalog[$id]);
}
Step 4: Show Full Catalog
To the top of the array_category function, we'll add an early return if the category passed in is "null", which means we are on the full catalog page. This will return all array_keys() in the catalog without having to perform any other tasks.
inc/functions.php
if ($category === null) {
return array_keys($catalog);
}
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