views:

66

answers:

2

I want to create a "guide bar" (I don't know its right name). I've got a table called cat that has the following data:

catid        catname         parentid
1            news            null
2            sport           1
3            health          1
4            tennis          2
5            football        2
6            soccer          5

My page receives: $catid=6, and I want to create:

news>sport>football>soccer
+1  A: 

They are called bread crumbs. There's a tutorial here that may help: http://www.mindpalette.com/tutorials/breadcrumbs/index.php

klausbyskov
Thanks for the guide,but the link that you suggest i think work on page hierarchy ,suppose that i have only one page for sport but sport has 3 levels so how it possible that i show the 3 levels with the same page?
Kaveh
+3  A: 

First get your data from database and build an array

$q = mysql_query("SELECT catid, catname, parentid FROM cat");
$pages = array();
while($r = mysql_fetch_assoc($q)) {
    $pages[$r['catid']] = array('catname' => $r['catname'], 'parentid' => $r['parentid']);
}

Use a recursive function to build the breadcrumbs:

function build_breadcrumbs($pages, $catid) {
    if(is_null($catid) || empty($catid)) return;
    return build_breadcrumbs($pages, $pages[$catid]['parentid']).$pages[$catid]['catname'].' > ';
}

The function returns the parent's breadcrumbs + the current breadcrumb. Use the function like this:

$catid = 6;
$breadcrumbs = trim(build_breadcrumbs($pages, $catid), ' >');
echo $breadcrumbs;

Or, if you like arrays more, you can create a function like this:

function build_breadcrumbs($pages, $catid) {
    if(is_null($catid) || empty($catid)) return array();
    return array_merge(build_breadcrumbs($pages, $pages[$catid]['parent']), array($pages[$catid]['name']));
}

and use it with implode:

$catid = 6;
$breadcrumbs = implode(' > ', build_breadcrumbs($pages, $catid));
echo $breadcrumbs;

That gives you the option to define the separator outside the function. Hope that helps.

Tatu Ulmanen
Tatu Ulmanen; thanks a lot i used the last suggestion and it works very well,i it possible that guide me how`can i attach a link to each catname ? so when user click on e.g football go to football page.
Kaveh
in build_breadcrumbs function, replace `$pages[$catid]['name']` with `<a href="URL HERE">'.$pages[$catid]['name'].'</a>`.
Tatu Ulmanen