Let's say we have the following array of categories. Normally this might be stored in a database, but we'll use an array here for simplicity.
Code: Select all
/* Example category hierarchy:
Tutorials
- PHP
-- OOP
-- Tips
- JavaScript
-- Basics
-- Frameworks
--- jQuery
--- MooTools
News
- PHP
- Wordpress
*/
$cats = array();
$cats[1] = array('parent' => 0, 'title' => 'Tutorials');
$cats[2] = array('parent' => 1, 'title' => 'PHP');
$cats[3] = array('parent' => 2, 'title' => 'OOP');
$cats[4] = array('parent' => 2, 'title' => 'Tips');
$cats[5] = array('parent' => 1, 'title' => 'JavaScript');
$cats[6] = array('parent' => 5, 'title' => 'Basics');
$cats[7] = array('parent' => 5, 'title' => 'Frameworks');
$cats[8] = array('parent' => 7, 'title' => 'jQuery');
$cats[9] = array('parent' => 7, 'title' => 'MooTools');
$cats[10] = array('parent' => 0, 'title' => 'News');
$cats[11] = array('parent' => 10, 'title' => 'PHP');
$cats[12] = array('parent' => 10, 'title' => 'Wordpress');
Our recursive function would check if parent is greater than 0. If so, the function would return the current category prepended by the result of calling itself with the parent id. If parent is 0, it will just return the name of the category. This way, it will keep adding categories to the chain until it gets to the top. Here's what it looks like:
Code: Select all
function breadcrumbs($id) {
global $cats;
if($cats[$id]['parent'] > 0) {
return breadcrumbs($cats[$id]['parent']) . ' -> ' . $cats[$id]['title'];
}
return $cats[$id]['title'];
}
Here is a full example:
Code: Select all
<?php
/* Example category hierarchy:
Tutorials
- PHP
-- OOP
-- Tips
- JavaScript
-- Basics
-- Frameworks
--- jQuery
--- MooTools
News
- PHP
- Wordpress
*/
$cats = array();
$cats[1] = array('parent' => 0, 'title' => 'Tutorials');
$cats[2] = array('parent' => 1, 'title' => 'PHP');
$cats[3] = array('parent' => 2, 'title' => 'OOP');
$cats[4] = array('parent' => 2, 'title' => 'Tips');
$cats[5] = array('parent' => 1, 'title' => 'JavaScript');
$cats[6] = array('parent' => 5, 'title' => 'Basics');
$cats[7] = array('parent' => 5, 'title' => 'Frameworks');
$cats[8] = array('parent' => 7, 'title' => 'jQuery');
$cats[9] = array('parent' => 7, 'title' => 'MooTools');
$cats[10] = array('parent' => 0, 'title' => 'News');
$cats[11] = array('parent' => 10, 'title' => 'PHP');
$cats[12] = array('parent' => 10, 'title' => 'Wordpress');
function breadcrumbs($id) {
global $cats;
if($cats[$id]['parent'] > 0) {
return breadcrumbs($cats[$id]['parent']) . ' -> ' . $cats[$id]['title'];
}
else {
return $cats[$id]['title'];
}
}
// Examples
echo breadcrumbs(1); // Tutorials
echo breadcrumbs(8); // Tutorials -> JavaScript -> Frameworks -> jQuery
echo breadcrumbs(11); // News -> PHP
?>