2016-02-12 45 views
1

我想在PHP中創建多個循環來選擇父項和子項。我有這樣的代碼:SELECT查詢並在PHP中創建一個無限循環

<?php 
$counter = 0; 
$sql="SELECT * from shop_categories where parent = '' order by name ASC "; 
$rs=mysql_query($sql,$conn); 
while($result = mysql_fetch_array($rs)) { 
    $flag = 1; 
    $current_parent_sequence = $result["sequence"]; 

    echo '<strong>'.$result["name"].'</strong><br>'; 

    while($flag == 1) { 
     $counter++; 

     $sql2="SELECT * from shop_categories where parent = '".$current_parent_sequence."' order by name ASC "; 
     $rs2=mysql_query($sql2,$conn); 
     if(mysql_num_rows($rs2) > 0) { 
      while($result2=mysql_fetch_array($rs2)) { 
       $current_parent_sequence = $result2["sequence"]; 

       echo $counter.' - '.$result2["name"].'<br>'; 
      } 
     } else { 
      $flag = 0; 
     } 
    } 
} 
?> 

然後我在我的表這個數據 - http://postimg.org/image/o2p31xd1j/

所以應該顯示父項及其子項及其子項等,但其只顯示:

Cat 1 
1 - Sub Cat 1 
1 - Sub Cat 2 
Cat 2 
Cat 3 
4 - Sub Cat 1 
+0

好的,所以你第二個循環的問題是它沒有檢查子子項目,直到所有的子項目都被檢查過,所以到了檢查子子項目的時候,它在'Sub Cat 2'上,它沒有任何子項。像@Apb建議的遞歸函數將幫助您檢查每個條目的表格,而不是在最後一個條目之後。 –

回答

2

請嘗試下面的代碼。它可能會幫助你。你需要創建函數遞歸調用。

function getChild($conn, $id) { 
    $rs=mysqli_query($conn, "SELECT * from test_tbl where parent = '$id' order by name ASC "); 
    while($result = mysqli_fetch_assoc($rs)) { 
     $current_parent_sequence = $result["sequence"]; 
     $parent = $result["parent"]; 
     echo "--" . $result["name"] . "<br>"; 
     if($parent != 0) 
      getChild($conn, $current_parent_sequence); 
    } 
} 

$rs=mysqli_query($conn, "SELECT * from test_tbl where parent = '' order by name ASC "); 
while($result = mysqli_fetch_assoc($rs)) { 
    $current_parent_sequence = $result["sequence"]; 
    $parent = $result["parent"]; 
    echo $result["name"] . "<br>"; 
    getChild($conn, $current_parent_sequence); 
} 

使用mysqlimysql已被棄用。

+0

'mysql_ *'已被刪除,不推薦使用。 – Tom