没什么好问的。我想要打印数组,但不使用递归。原因是程序存在错误,因为它需要重写过多的数据和旧函数。该函数称为递归函数,在多次调用后,我的脚本无法分配更多内存,因此我的示例数组是:
array (
0 =>
array (
'id' => '5713008',
'children' =>
array (
0 =>
array (
0 =>
array (
'id' => '13',
'children' =>
array (
'id' => '20',
'children' =>
array (
0 =>
array (
'id' => '120',
),
1 =>
array (
'id' => '464',
),
),
),
),
1 =>
array (
0 =>
array (
'id' => '21',
),
),
),
1 =>
array (
'id' => '143',
'children' =>
array (
1 =>
array (
'id' => '60011',
),
2 =>
array (
'id' => '60012',
),
3 =>
array (
'id' => '5299316',
),
4 =>
array (
'id' => '5712901',
),
5 =>
array (
'id' => '147',
),
6 =>
array (
'id' => '148',
),
7 =>
array (
'id' => '149',
),
8 =>
array (
'id' => '60010',
),
),
),
),
),
)
我需要这样的数据:
id: 5713008
--------------
>>id: 13
--------------
>>>>id: 20
--------------
>>>>>>>>id: 120
--------------
>>>>>>>>id: 464
--------------
>>>>id: 21
--------------
>>id: 143
--------------
>>>>id: 60011
--------------
>>>>id: 60012
--------------
>>>>id: 5299316
--------------
>>>>id: 5712901
--------------
>>>>id: 147
--------------
>>>>id: 148
--------------
>>>>id: 149
--------------
>>>>id: 60010
--------------
答案 0 :(得分:1)
function myVarDump($item, $recursion = 0)
{
if(is_array($item))
foreach($item as $key => $value)
{
if(is_array($value))
myVarDump($value, $recursion+1);
else
echo str_repeat('>', $recursion)."$key: $value\n--------------\n";
}
else echo($item);
}
此函数将根据您的请求输出数据,但显然您仍需要递归才能显示嵌套项。因此,我并不完全理解您要解决的问题 - 也许您需要限制递归?如果是这样,只需添加一个限制$recursion
在此函数中的高度,例如:
function myVarDump($item, $recursion = 0, $maxRecursion = 5)
{
if($recursion > $maxRecursion)
echo str_repeat('>>', $recursion)."ERROR: Max recursion $maxRecursion exceeded";
elseif(is_array($item))
foreach($item as $key => $value)
{
if(is_array($value))
myVarDump($value, $recursion+1);
else
echo str_repeat('>', $recursion)."$key: $value\n--------------\n";
}
else echo($item);
}