Search code examples
phparraysrecursion

A recursive walk-through over a 10000 element array in PHP: Maximum function nesting level reached


I have a sorted array of 2-element arrays like the following:

array(
  array('id' => 1734, 'count' => 14),
  array('id' => 1734, 'count' => 7),
  array('id' => 9374, 'count' => 5),
  array('id' => 9374, 'count' => 253)
);

The array is sorted on the 'id' field of the inner arrays. The goal is to reduce it to the following:

array(
  array('id' => 1734, 'count' => 21),
  array('id' => 9374', 'count' => 258)
);

I.e. to aggregate/summ over the 'count' element for every unique 'id'.

I go though the array in a function myfunc(array $arr){...} which does array_shift($arr) and then calls myfunc($arr). It also has an appropriate check for the base case of the recursion (an empty array) and should terminate at this point.

The thing is that I have tens of thousands of the inner arrays and PHP throws "PHP Fatal error: Uncaught Error: Maximum function nesting level of '256' reached, aborting!".

After carefully examining the code and running a debug session I saw that the $arr does really reduce it's size from call to call, so I think the problem does lie only on the maximum function nesting setting. However it seems for me that it is impractical to change this setting to something like 1 million. So, what other solution could we have here?


Solution

  • Thank you for the answers. One thing that I have obviously failed to mention is that I want the solution to be in functional style.

    I have equivalently (in the terms of result) rewrote the algorithm to use array_reduce(). This allows me to stay in functional style and have the thing done.