O
O
Outoverlay2016-01-27 20:20:45
PHP
Outoverlay, 2016-01-27 20:20:45

How to store values ​​in recursion?

Wrote a function to create a tree menu. After that, it was necessary to find out the nesting level, I wrote a function that returns the number of nestings. Now we need it to return not only the number of nestings, but also an array of this type: array( 'count' => n, 'level_ids' => array(1,2,3...)).
The fact is that with recursion, all data cannot be packed into an array (it turns out to be nested).
So instead of: array( 'count' => n, 'level_ids' => array(1,2,3...)) I get: array( 'count' => n, 'level_ids' => array( array (1 => array(2=> array(3)))) I found an option how to use a double function and first get a string of this type 1,2,3 and then turn it into an array using explode. But ... I would like to refuse from redundant features.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
C
Cat Anton, 2016-01-27
@Outoverlay

The fact is that with recursion, all data cannot be packed into an array (it turns out to be nested).

Can. Here's a simple example for you:
function example($n)
{
    return ($n > 0) ? array_merge([$n], example($n - 1)) : [];
}

example(5); // [5, 4, 3, 2, 1]

C
Curly Brace, 2016-01-27
@stasuss

and the global variable will not work? or static?

X
xmoonlight, 2016-01-27
@xmoonlight

array_push() to an array with passing when called recursively..

D
Dmitry, 2016-01-27
@mytmid

You can use static in recursive functions :
php.net/manual/ru/language.variables.scope.php#exa...
Example:

function test()
{
    static $count = 0, $data = [];
    $data[] = 'data:'.++$count;
  if( $count < 5 ) test();
  return $data;
}

echo '<pre>';
print_r(test());

PS I do not rule out that I could misunderstand the question :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question