1

To list all categories on my website I iterate through category hierarchy with the following function:

$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
    }
}

The problem is that $x is incremented in the following manner:

// 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

How can I make $x to increment in straight sequence (e.g. 1,2,3,4,5,6,7,8,9,10) across all loops both parent and nesting?

qwaz
  • 1,285
  • 4
  • 23
  • 47

2 Answers2

2

You need to make $x a reference parameter, so that assigning it in the function updates the caller's variable.

function list_categories($categories, &$x) {
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I just tried it, but I get the error: `call-time pass-by-reference has been removed` – qwaz May 21 '15 at 17:35
  • I don't think you should get that from my change. See http://stackoverflow.com/questions/8971261/php-5-4-call-time-pass-by-reference-easy-fix-available – Barmar May 21 '15 at 17:36
  • You would get that error if you wrote `list_categories ($category['children'], &$x);` – Barmar May 21 '15 at 17:37
  • @dmit when you call your function, do not call the function using `&$x`. Only use the `&$x` when defining the function. – Brock B. May 21 '15 at 17:38
0

Pass $x through your call to the function.

list_categories($category['children']); should be passing $x as a parameter.

Brock B.
  • 367
  • 1
  • 13
  • Sorry I forgot to write it in my question. I do that already in my app. I've edited the code in my post. – qwaz May 21 '15 at 17:30
  • If he didn't do that he would get an error due to passing the wrong number of arguments. – Barmar May 21 '15 at 17:30
  • See the other answer - it needs to be passed by reference. – Brock B. May 21 '15 at 17:31
  • @Barmar - it was just what I immediately noticed when looking at the question before he made his edits. I saw you added your answer before I was able to update to add the `&` to make the variable a reference. Sorry. – Brock B. May 21 '15 at 17:34