这真让我抓狂。递归函数在 5.4.4 和 5.1.6(我无法控制的客户端的托管服务器)中的工作方式似乎有所不同。除了举例,我无法真正解释它:
<?php
$simpsons[0] = array("name"=>"Abe","parent"=>-1);
$simpsons[1] = array("name"=>"Homer","parent"=>0); // Homer's parent is Abe
$simpsons[2] = array("name"=>"Bart","parent"=>1); // Bart's parent is Homer
$simpsons[3] = array("name"=>"Lisa","parent"=>1); // Lisa's parent is Homer
$simpsons[4] = array("name"=>"Maggie","parent"=>1); // Maggie's parent is Homer
function get_children($parent) {
global $simpsons;
foreach ($simpsons as $index=>$onesimpson) {
if ($onesimpson["parent"]==$parent) {
echo "$onesimpson[name] is a child of ".$simpsons[$parent]["name"].".<br />\n";
get_children($index);
}
}
}
get_children(0);
?>
在 PHP 5.4.4 上,输出是
Homer is a child of Abe.
Bart is a child of Homer.
Lisa is a child of Homer.
Maggie is a child of Homer.
而在 PHP 5.1.6 上的输出是
Homer is a child of Abe.
Bart is a child of Homer.
我不擅长术语,所以我无法解释发生了什么(就像在 5.1.6 中,即使被调用函数完成,被调用函数也会改变调用函数的参数),但我已经在 PHP 沙箱在线测试过在这两个版本上,问题是相同的 - 它不是特定于我的设置或托管服务器设置。