Recursive loop in php using multidimensional array
===

I have a DB structure in this way.
    
    stopid  | parentid
    2       |        1
    3       |        1
    5       |        2
    9       |        2
    8       |        2
    11      |        3
    11      |        9


I want to search starting stop and final stop. that is something sort or programmatically search. I have first stop as parent id. and final stop as stopid.
As I have to search first stop from 1 to 11 so I put logic as starting from final stop 11 and then recurse the loop. Is their any logic. I have tried but not successfull with it. It doesn't need to final all root. I just want any first root that is compatiable. like..

1 -> 3 -> 11 or 1 -> 2 -> 9 ->11 in this way...


	extract($_POST);
	echo "From :$from to $to".'<br/>';
	$sql="select parentid, stopid from routes WHERE stopid = '".$to."' ";
	echo $sql.'<br/>';
	$result = mysql_query($sql) or die(mysql_error());
 	$count = mysql_num_rows($result) or die( mysql_error());
	$stopid = array(); 
	while( $row = mysql_fetch_array($result)) {
		$stopid[$row['stopid']][] = $row['parentid'];
	}
	echo '<pre>';
	
	$countarray = count($stopid); 
	while($countarray >= 1){
		foreach($stopid as $finalstop_value){
			foreach($finalstop_value as $finalstop_ky => $finalstop_vl){
				$query = "SELECT * FROM routes WHERE stopid = '".$finalstop_vl."'";
				$sql = mysql_query($query) or die(mysql_error());
				echo $query. ' Gives '.mysql_num_rows($sql).' rows...<br/>';
				while( $row = mysql_fetch_array($sql))	{ 
					$new_stopid[$finalstop_vl][$row['stopid']][] = $row['parentid']; 
				}
				echo '<pre>';
				print_r($new_stopid);
                                // $stopid[$finalstop_vl][] = $new_stopid;
				$countarray--; 
			}
		}
		
	}		
    print_r($stopid);
    exit;
