如何在Codeigniter中显示无限子类别?

时间:2015-11-15 14:06:12

标签: php 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;?>

问题是它只显示一个级别子类别。如何显示无限嵌套类别

2 个答案:

答案 0 :(得分:2)

欢迎来到recursion的精彩世界!

另见What is recursion and when should I use it?

您需要的是一个可以使用子集或精炼变量集调用自身的函数。 这听起来比实际更难。您需要多次调用相同的函数,并将其返回输出作为自身内部的变量。

<?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 );
}

答案 1 :(得分: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
          )
         )