2012-07-28 112 views
0

我有这种方式的数据库结构。使用多维数组在php中递归循环

stopid | parentid 
2  |  1 
3  |  1 
5  |  2 
9  |  2 
8  |  2 
11  |  3 
11  |  9 

我想搜索出发站点和最终站点。这是排序或编程搜索。我有第一站作为父母身份证。并最终停止为stopid。 因为我必须从1到11搜索第一站,所以我把逻辑从最后一站11开始,然后递归循环。是他们的任何逻辑。我尝试过但没有成功。它不需要最终所有的根。我只想要任何第一个可以兼容的根。如..

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

你想找到一个完整的序列直到根(1-3-11),或者只是* any * root(在你的例子中是1)? – galymzhan 2012-07-28 14:17:58

+0

我不想获得所有root(可选 - 如果U可以找到所有根目录)。否则我想要至少一个根(不管它是远或短),但我想要序列。 – 2012-07-28 14:22:38

回答

0

从我的理解,你有一个n元树结构您需要扫描搜索连接某些2个节点的路径。那么,这是一个传统的算法问题,许多解决方案都在那里等着你;-)

如果在你的树中没有你没有提到的特定属性,我建议实现一个Breadth-first search

+0

我知道我已经尝试过,但是我被卡住在编程上并不合理。我将如何操作我的代码来这样做。 – 2012-07-28 14:29:07

+0

根据问题的大小(节点数量等),您可以在内存中构建树结构,或者即时查询数据库中关于节点之间的连接。然后建立一堆要访问的节点,并在一个循环中访问它们;-)我希望这很清楚我的意思。 – emesx 2012-07-28 14:32:23