2. 编辑:
我修改了我的迭代解决方案,以便检查文本格式的结果数组的总长度。如果长度没有改变,迭代将退出。
(修改)示例数据:
$a=array('18'=> array ( '1' =>'', '14' =>''),
'20' => array ( '32' =>''),
'23' => array ( '24' =>''),
'24' => array ( '25' =>'', '26' =>''),
'26' => array ( '27' =>'', '28' =>''),
'29' => array ( '33' =>''),
'30' => array ( '23' =>'', '31' =>''),
'32' => array ( '30' =>''),
'33' => array ( '32' =>'')
);
代码:
function plough(&$a){ // ploughs throught the array once from top to bottom ...
foreach ($a as $ak => &$av){
foreach($av as $k => &$v) {
if(isset($a[$k])) $v=$a[$k];
}
}
return strlen(print_r($a,1)); // returns string-length of print_r-output
}
// iterate until there is no change in string-length any more ...
for ($al1=1+$al0=0 ;$al0<$al1; $al1=plough($a)) $al0=$al1;
print_r($a);
通过将&
变量名称放在foreach
循环中,您正在使用对这些变量的引用,而不是使用复制的值。将例程应用于我的(修改后的)示例会导致以下结果
输出:
Array
(
[18] => Array
(
[1] =>
[14] =>
)
[20] => Array
(
[32] => Array
(
[30] => Array
(
[23] => Array
(
[24] => Array
(
[25] =>
[26] => Array
(
[27] =>
[28] =>
)
)
)
[31] =>
)
)
)
[23] => Array
(
[24] => Array
(
[25] =>
[26] => Array
(
[27] =>
[28] =>
)
)
)
[24] => Array
(
[25] =>
[26] => Array
(
[27] =>
[28] =>
)
)
[26] => Array
(
[27] =>
[28] =>
)
[29] => Array
(
[33] => Array
(
[32] => Array
(
[30] => Array
(
[23] => Array
(
[24] => Array
(
[25] =>
[26] => Array
(
[27] =>
[28] =>
)
)
)
[31] =>
)
)
)
)
[30] => Array
(
[23] => Array
(
[24] => Array
(
[25] =>
[26] => Array
(
[27] =>
[28] =>
)
)
)
[31] =>
)
[32] => Array
(
[30] => Array
(
[23] => Array
(
[24] => Array
(
[25] =>
[26] => Array
(
[27] =>
[28] =>
)
)
)
[31] =>
)
)
[33] => Array
(
[32] => Array
(
[30] => Array
(
[23] => Array
(
[24] => Array
(
[25] =>
[26] => Array
(
[27] =>
[28] =>
)
)
)
[31] =>
)
)
)
)