[英]how to display categories,sub categories and sub sub categories - codeigniter
[英]How to show infinite sub categories in 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;?>
问题是它只显示一级子类别。如何显示无限嵌套类别
欢迎来到精彩的递归世界!
另请参阅什么是递归以及何时应使用它?
您需要的是一个可以用变量的子集或精确集合调用的函数。 这听起来比实际困难得多。 您需要多次调用同一函数,并将其返回输出用作自身内部的变量。
<?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 );
}
$category['sub_categories']
使此子类别为关联数组,以便您可以在此数组上应用for-each循环,应像这样
$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
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.