我有这样的数据库结构。
stopid | parentid
2 | 1
3 | 1
5 | 2
9 | 2
8 | 2
11 | 3
11 | 9
我想搜索开始停止和最后一站。这是一种排序或编程搜索。我有第一站作为父ID。最终停止了。 因为我必须从1到11搜索第一站,所以我将逻辑从最后一站11开始,然后递归循环。是他们的任何逻辑。我试过但没有成功。它不需要最终所有root。我只想要任何兼容的第一个root。像..
1 - > 3 - > 11或1 - > 2 - >以这种方式9 - > 11 ......
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;
答案 0 :(得分:0)
根据我的理解,你有一个n-ary树结构,你需要扫描搜索连接2个节点的路径。嗯,这是一个经典的算法问题,很多解决方案都在等着你; - )
如果您的树中没有您在帖子中未提及的特定属性,我建议您实施Breadth-first search。