2015-11-15 37 views
1

我的代碼是如何在Codeigniter中顯示無限的子類別?

<?php foreach ($categories as $category):?> 
    <tr> 
     <td><?php echo $category['name'];?></td> 
    </tr> 
    <?php if(isset($category['sub_categories'])):?> 

    <?php foreach($category['sub_categories'] as $subcategory):?> 
     <tr> 
      <td style="margin-left:50px;padding-left:50px;"><span><?php echo $subcategory['name'];?></span></td> 
     </tr> 
    <?php endforeach;?> 
    <?php endif;?> 

<?php endforeach;?> 

的問題是,它僅顯示一個級別subcategories.How我展示無限嵌套類

回答

2

歡迎的精彩世界!

看你需要的是一個可以調用本身的子集或精煉組變量的函數。 這聽起來比實際上更困難。你需要多次調用同一個函數,並且使用它的返回輸出作爲一個變量。

<?php 

# Recursive function to show each category and sub-categories 
function showCategory($category, $offset = 0) { 
    $html = ''; 

    # Open the column 
    if ($offset > 0) { 
     $html .= '<td style="margin-left: ' . $offset . 'px; padding-left: ' . $offset . 'px;">'; 
     $html .= '<span>'; 
    } else { 
     $html .= '<td>'; 
    } 

    $html .= $category['name']; 

    if (isset($category['sub_categories'])) { 
     foreach ($category['sub_categories'] as $sub_category) { 
      # Wrap table around the results 
      $html .= '<table>'; 

      # Add 50 pixels to each recursion - call this function with sub_category as parameter 
      $html .= showCategory($sub_category, $offset + 50); 
      $html .= '</table>'; 
     } 
    } 

    if ($offset > 0) { 
     $html .= '</span>'; 
    } 

    # Close the column 
    $html .= '</td>'; 

    # Return the row 
    return '<tr>' . $html . '</tr>'; 
} 

# Test data: 
$categories = [ 
    [ 
     'name'   => 'foo', 
     'sub_categories' => [ 
      ['name' => 'sub1'], 
      [ 
       'name'   => 'sub2', 
       'sub_categories' => [ 
         ['name' => 'subsub1'], 
         ['name' => 'subsub2'] 
       ] 
      ] 
     ] 
    ] 
]; 

# This is where we show stuff 
foreach ($categories as $category) { 
    echo showCategory($category); 
} 
0
$category['sub_categories'] 

使這個子類作爲關聯數組,這樣就可以申請,每個在這個 數組循環應該是這樣的

$categoryArr=array(
     'name'=>'category name', 
     'subcategory'=>array(
       array(
        'name'=>'subcategory name', 
        'details'=>'enter details here' 
       ), 
       array(
        'name'=>'subcategory2 name', 
        'details'=>'enter details here' 
       ) 
       ..... so on 
     ) 
     ) 
+0

我不能理解如何使loop.Kindly精心製作 –

相關問題