2015-02-24 94 views
-1

我已經寫了一個php函數來顯示類別,所有的作品找到,但回聲顯示像這樣顛倒(椅子/傢俱/產品),但我需要它倒過來看起來像這樣(產品/傢俱/椅)php遞歸函數的逆向結果

function sitemap($id) { 
    $query_rsCategoryId = "SELECT * FROM categories 
    WHERE category_id = '".$id."'"; 
    $rsCategoryId = mysql_query($query_rsCategoryId, $connection); 
    $row_rsCategoryId = mysql_fetch_assoc($rsCategoryId); 
    $parent = $row_rsCategoryId['category_parent']; 

    echo '<li><span class="divider">/</span> 
    <a href="products.php?category_id='.$row_rsCategoryId['category_id'].'"> 
    '.$row_rsCategoryId['category_name_en'].' </a> 
    </li>'; 

    if ($parent == 0) { 
    exit; 
    } else { 
    return sitemap($parent); 
    } 
} 
+0

而不是回顯結果,建立一個遞歸結果數組,然後您可以顛倒該數組的順序,然後循環顯示結果的數組 – 2015-02-24 16:40:15

+1

在遞歸函數調用後放置回聲。 (也將返回值保存到一個變量並最終返回它,但它似乎沒有做任何事情,也反轉條件:如果$ parent!= 0,然後sitemap($ parent)) – 2015-02-24 16:41:05

回答

1

使用順序只需修改代碼有點...

function sitemap($id) { 
    $query_rsCategoryId = "SELECT * FROM categories 
    WHERE category_id = '".$id."'"; 
    $rsCategoryId = mysql_query($query_rsCategoryId, $connection); 
    $row_rsCategoryId = mysql_fetch_assoc($rsCategoryId); 
    $parent = $row_rsCategoryId['category_parent']; 


    if ($parent != 0) { 
     sitemap($parent); 
     echo '<li><span class="divider">/</span>'; 
    } else { 
     echo '<li>'; 
    } 

    echo '<a href="products.php?category_id='.$row_rsCategoryId['category_id'].'"> 
    '.$row_rsCategoryId['category_name_en'].' </a> 
    </li>'; 
} 
+0

偉大的作品完美:)謝謝 – 2015-02-24 16:59:37

0

嘗試通過遞減在查詢

SELECT * FROM categories 
WHERE category_id = '".$id."' ORDER BY category_name_en DESC 
+0

贏得'工作,他正在一個單獨的查詢中獲取每個類別。 – vicvicvic 2015-02-24 18:21:16