簡體   English   中英

PHP遞歸函數問題?

[英]PHP recursive function problem?

我想在我的第一個和第四個<ol>標簽中添加兩個不同的類屬性,但我真的不知道如何在遞歸函數中添加它? 有人能幫我嗎?

這是我的PHP腳本。

function make_list ($parent = 0, $parent_url = '') {
    global $link;
    echo '<ol>';

    foreach ($parent as $id => $cat) {
        if($cat['parent_id'] == '0'){
            $url = $parent_url . $cat['url'];
            echo '<li><a href="' . $url . '" title="' . $cat['category'] . ' Category Link" style="color: orange; font-weight: bold;">' . $cat['category'] . '</a>';            
        } else {
            $url = $parent_url . $cat['url'];
            // Display the item:
            echo '<li><a href="' . $url . '" title="' . $cat['category'] . ' Category Link">' . $cat['category'] . '</a>';
        }

        if (isset($link[$id])) {
            make_list($link[$id], $url);
        }               
        echo '</li>';
    }       
    echo '</ol>';
}

$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM categories ORDER BY parent_id, category ASC");
if (!$dbc) {
    print mysqli_error();
} 

$link = array();

while (list($id, $parent_id, $category, $url, $depth) = mysqli_fetch_array($dbc)) {
    $link[$parent_id][$id] =  array('parent_id' => $parent_id, 'category' => $category, 'url' => $url, 'depth' => $depth);
}

make_list($link[0]);

產量

<ol>
   <li>First Nested List</li>
   <li>First Nested List</li>
   <li>First Nested List
      <ol>
        <li>Second Nested List</li>
        <li>Second Nested List</li>
        <li>Second Nested List
          <ol>
            <li>Third Nested List</li>
            <li>Third Nested List</li>
            <li>Third Nested List
              <ol>
                <li>Fourth Nested List</li>
                <li>Fourth Nested List</li>
                <li>Fourth Nested List</li>
              </ol>
            </li>
            <li>Third Nested List</li>
            <li>Third Nested List</li>
          </ol>
        </li>
        <li>Second Nested List</li>
        <li>Second Nested List</li>
      </ol>
   </li>
   <li>First Nested List</li>
   <li>First Nested List</li>
</ol>

只需添加深度作為參數。 然后檢查它是0或4還是你需要的任何東西。

function make_list ($parent = 0, $parent_url = '', $depth=0) {
...
make_list($link[$id], $url, $depth+1);
...

添加全局$num_links變量。 每當您發出<ol> ,請增加它。 在達到所需值時添加屬性。

但是,如果你這樣做,你所選擇的功能與你正在解決的任務之間可能存在不匹配......“第一個或第四個”可能不是你要檢查的真實條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM