Answer the question
In order to leave comments, you need to log in
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
The fact is that with recursion, all data cannot be packed into an array (it turns out to be nested).
function example($n)
{
return ($n > 0) ? array_merge([$n], example($n - 1)) : [];
}
example(5); // [5, 4, 3, 2, 1]
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());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question