recursion - PHP recursive function nesting level reached -
good day. have parcer function taker array of string this:
['str','str2','str2','*str','*str2','**str2','str','str2','str2']
and recursivelly elevates level starting asterix this
['str','str2','str2',['str','str2',['str2']],'str','str2','str2']
and function is:
function recursive_array_parser($array) { { $i = 0; $s = null; $e = null; $err = false; foreach ($array $item) { if (!is_array($item)) { //if element not array $item = trim($item); if ($item[0] === '*' && $s == null && $e == null) { //we it's start , end if has asterix $s = $i; $e = $i; } elseif ($item[0] === '*' && $e != null) $e = $i; elseif (!isset($array[$i + 1]) || $s != null && $e != null) { //if there no elements or asterix element ended elevate $e = $e == null ? $i : $e; $head = array_slice($array, 0, $s); $_x = []; $inner = array_slice($array, $s, $e - $s + 1); foreach ($inner $_i) $_x[] = substr($_i, 1); $inner = [$_x]; $tail = array_slice($array, $e + 1, 999) or []; $x = array_merge($head, $inner); $array = array_merge($x, $tail); $s = null; $e = null; $err = true; } } else { $array[$i] = recursive_array_parser($array[$i]); //if item array of items recur. } $i++; if ($err == true) { break 1; } } } while ($err); return $array; }
when function runs, "fatal error: maximum function nesting level of '200' reached, aborting!" error.
i know has infinite recursion, can't track particular place occurs, , strange.
i don't rewrite code, code can reduced , simplified while, can see, getting desired result. see if works you:
$a = array('a','b','c','*d','*e','**f','g','*h'); print_r($a); $a = recursive_array_parser($a); print_r($a); function recursive_array_parser($array) { $ret = array(); for($i=0; $i<sizeof($array); $i++) { if($array[$i]{0}!='*') $ret[] = $array[$i]; else { $tmp = array(); for($j=$i; $j<sizeof($array) && $array[$j]{0}=='*'; $j++) { $tmp[] = substr($array[$j],1); } $ret[] = recursive_array_parser($tmp); $i = $j-1; } } return $ret; }
note isn't possible $array[$i] array, check removed. recursion takes place on temp array created when * found. $i closer tied $array reset after parsing series of * elements.
Comments
Post a Comment