Чтобы перечислить все категории на моем веб-сайте, я перебираю иерархию категорий со следующей функцией:
$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
ссылочным параметром, чтобы его назначение в функции обновляло переменную вызывающего.
function list_categories($categories, &$x) {
Передайте $ x через ваш вызов функции.
list_categories($category['children']);
должен передаваться в качестве параметра $ x.
call-time pass-by-reference has been removed