我有這種方式的數據庫結構。使用多維數組在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;
你想找到一個完整的序列直到根(1-3-11),或者只是* any * root(在你的例子中是1)? – galymzhan 2012-07-28 14:17:58
我不想獲得所有root(可選 - 如果U可以找到所有根目錄)。否則我想要至少一個根(不管它是遠或短),但我想要序列。 – 2012-07-28 14:22:38