【发布时间】:2015-05-21 17:25:02
【问题描述】:
为了列出我网站上的所有类别,我使用以下函数遍历类别层次结构:
$x = 1;
function list_categories($categories, $x) {
foreach($categories as $category) {
$cat_list .= '<li>'.$category['name'].'<li>';
if (count($category['children']) > 0) {
$cat_list .= '<ul>'
list_categories($category['children'], $x);
$cat_list .= '</ul>'
}
$x++; // incremention of $x
}
}
问题是$x按以下方式递增:
// ITERATION #1
parent: $x = 1
| // nesting loop #1
|--> child $x = 2
| // sub-nesting loop #1
|--> descendant $x = 3
// ITERATION #2
parent: $x = 2
| // nesting loop #2
|--> child $x = 3
| // sub-nesting loop #2
|--> descendant $x = 4
// ITERATION #3
parent: $x = 3
| // nesting loop #3
|--> child $x = 4
| // sub-nesting loop #3
|--> descendant $x = 5
如何使$x 在所有父循环和嵌套循环中以直线顺序递增(例如 1、2、3、4、5、6、7、8、9、10)?
【问题讨论】:
标签: php loops foreach nested-loops