简体   繁体   中英

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;

From what I understand you have a n-ary tree structure that you need to scan in search of a path connecting some 2 nodes. Well, this is a classical algorithmic problem and many solutions are there just waiting for you ;-)

If there are no specific properties in your tree that you haven't mentioned in the post, I'd suggest implementing a Breadth-first search .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM