Need a little help with recursion

Discussion in 'PHP' started by fireflyproject, Mar 3, 2009.

  1. #1
    function breadcrumbs($id) {
    		$sql = "select * from categories where id = '$id'"; // get row info about current category
    		$result = mysql_query($sql);
    		$r = mysql_fetch_array($result);
    		
    		if ($r['parent'] != 0) { //if the category has a parent
    			return $r['name'] . "/";
    			breadcrumbs($r['parent']);
    		} else { //else quit
    			return;
    		}
    	}
    PHP:
    I'm looking to get this function working with recursion.

    Right now when running this function I get only the first result and then the function quits.

    The end result should look something like this.

    Subcategory/Top Level Category

    Of course it should recurse for as many levels as there are, but if it does just these two levels, it will do them all.

    Any ideas why this isn't working?
     
    fireflyproject, Mar 3, 2009 IP
  2. magiatar

    magiatar Active Member

    Messages:
    68
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    73
    #2
    
    function breadcrumbs($id) {
            $sql = "select * from categories where id = '$id'"; // get row info about current category
            $result = mysql_query($sql);
            $r = mysql_fetch_array($result);
           
            if ($r['parent'] != 0) { //if the category has a parent
                return $r['name'] . "/". breadcrumbs($r['parent']);
    // Maybe you need to change this previous line to
    //         return breadcrumbs($r['parent'])."/".$r['name'];
    // and maybe you need to addapt a little to not have the / when it's not needed
            } else { //else quit
                return;
            }
        }
    
    Code (markup):

    I think this is that you are asking for.
    It's ok for you?
     
    magiatar, Mar 4, 2009 IP
  3. mehdiali

    mehdiali Peon

    Messages:
    99
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    if ($r['parent'] != 0) { //if the category has a parent
    breadcrumbs($r['parent']);//****************
    return $r['name'] . "/";//******************
    } else { //else quit
    return;
    }
     
    mehdiali, Mar 4, 2009 IP