如何在Codeigniter中显示无限子类别? [英] How to show infinite sub categories in Codeigniter?

查看:46
本文介绍了如何在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;?>

问题是它仅显示一级子类别.我如何显示无限嵌套类别

Issue is that it show only one level subcategories.How I show infinite nested categories

推荐答案

欢迎来到递归的美好世界

另请参见什么是递归以及何时应使用它?

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

What you need is a function that can call itself with a subset or refined set of variables. This sounds more difficult than it really is. You need to call the same function multiple times and using it's return output as a variable inside itself.

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

这篇关于如何在Codeigniter中显示无限子类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆