16 September, 2010

Create breadcrumb from array

Creating breadcrumbs can sometimes be really dificult. Breadcrumbs can be created from array in php using some simple code.
Following code can be used to create breadcrumbs from array, just a beginning though, and can be re-written further to make it
more flexible. Hope it helps someone like me.

$id = $_GET['id'];
if ( strlen( $id ) < 1 ) $id = "home";
//this array contains page lists, with id, title and parent page named as main in here
$pages = array(
'home' => array( 'id'=>"home", 'main'=>"my_home", 'title'=>"Home",
'url'=>"bcrumb.php?id=home" ),
'members' => array( 'id'=>"users", 'main'=>"home", 'title'=>"Members",
'url'=>"bcrumb.php?id=members" ),
'sudhir' => array( 'id'=>"jack", 'main'=>"users", 'title'=>"Sudhir",
'url'=>"bcrumb.php?id=sudhir" )
//function to create breadcrumb from array
function crumbs( $id, $pages ) {
$bCrumbList = array();
$pageid = $id;
while(strlen($pageid) > 0) {
$bCrumbList[] = $pageid;
$pageid = $pages[ $pageid ]['main'];
for($i = count( $bCrumbList ) - 1; $i >= 0; $i-- ) {
$page = $pages[$bCrumbList[$i]];
if ($i > 0) {
echo( " echo( $page['url'] );
echo( "\">" );
echo( $page['title'] );
if ( $i > 0 ) {
echo( "
| " );
echo "Crumbs:" .crumbs($id, $pages);
echo "
echo "Page:".$id;

Instead of using array, data can be loaded from xml file as well in order to create breadcrumbs, using the same function above.


pusp said...

Nice Article! It works

Thanks Blogger

Amit said...

How can I implement this in my website?

N.B: My web URLS are :

like these...
can I use this code to implement breadcrumb for my website?

Sudhir Bastakoti said...

Hi Amit,
Yes you can you it in your site. I see that you are using Joomla for development, and i suggest that you can use Joomla's extensions for displaying breadcrumbs, as the code will be more consistent and easier that way.
This is just a suggestion from my side.

Amit said...

I have totally customized this Web App.So, I did remove the admin section.This is a LIVE PROJECT.That's why I am asking you.How will I implemt this code to implement breadcrumb to parse this kind of URLs..?pls help me..