【发布时间】:2015-07-22 23:57:34
【问题描述】:
美好的一天。我有一个 parcer 函数,它接受一个这样的字符串数组:
['str','str2','str2','*str','*str2','**str2','str','str2','str2']
并且递归地提升那些以 asterix 开头的人的水平来获得这个
['str','str2','str2',['str','str2',['str2']],'str','str2','str2']
而功能是:
function recursive_array_parser($ARRAY) {
do {
$i = 0;
$s = null;
$e = null;
$err = false;
foreach ($ARRAY as $item) {
if (!is_array($item)) { //if element is not array
$item = trim($item);
if ($item[0] === '*' && $s == null && $e == null) { //we get it's start and end if it has asterix
$s = $i;
$e = $i;
} elseif ($item[0] === '*' && $e != null)
$e = $i;
elseif (!isset($ARRAY[$i + 1]) || $s != null && $e != null) { //if there are no elements or asterix element ended we elevate it
$e = $e == NULL ? $i : $e;
$head = array_slice($ARRAY, 0, $s);
$_x = [];
$inner = array_slice($ARRAY, $s, $e - $s + 1);
foreach ($inner as $_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 the item is array of items we recur.
}
$i++;
if ($err == true) {
break 1;
}
}
} while ($err);
return $ARRAY;
}
当此函数运行时,我收到“致命错误:已达到 '200' 的最大函数嵌套级别,正在中止!”错误。
我知道它与无限递归有关,但我无法跟踪它发生的特定位置,这很奇怪。
【问题讨论】:
-
如果你有
['*a', 'b', '*c'],应该变成['b', ['a','c']]还是[['a'], 'b', ['c']]? -
我认为 [[a],b,[c]] 因为星号显示水平。我错了吗?
-
@splash58 这似乎是他想要做的,但如果他想要
['b', ['a', 'c']],这会简单得多。该错误显然是由基于 $ARRAY 在 foreach 中更改 $ARRAY 而在不考虑 $ARRAY 本身的情况下增加 $i 引起的。 -
@kainaw 听到作者的声音会更好:))
-
@splash58 [['a'], 'b', ['c']]