在多个嵌套循环中递增 $x
increment $x across multiple nesting loops
为了列出我网站上的所有类别,我使用以下函数遍历类别层次结构:
$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)?
通过对函数的调用传递 $x。
list_categories($category['children']);
应该将 $x 作为参数传递。
您需要使 $x
成为引用参数,以便在函数中对其进行赋值会更新调用者的变量。
function list_categories($categories, &$x) {
为了列出我网站上的所有类别,我使用以下函数遍历类别层次结构:
$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)?
通过对函数的调用传递 $x。
list_categories($category['children']);
应该将 $x 作为参数传递。
您需要使 $x
成为引用参数,以便在函数中对其进行赋值会更新调用者的变量。
function list_categories($categories, &$x) {