PHP - 从递归函数返回数组时出错
经过两个小时的绞尽脑汁和谷歌搜索后——我被困住了!
根据标题,我试图返回一个在函数循环时构建的数组。我只想返回 else 上的数组变量,但它不会合作。它只是从函数中返回为空白,但是在 else 中我可以 print_r 它并按预期显示。它只是不会返回 $open_array 变量中的数组。任何想法(或滥用)将不胜感激!
function find_parent($number, $open = false) {
if(isset($other_variable[$number])) {
foreach($other_variable[$number] as $val) {
$open[$val->id] = [$val->id;
$open = find_parent([$val->id, $open);
}
}
else {
return $open;
}
}
$open_array = find_parent($number);
print_r($open_array);
After two hours of head scratching and googling - i'm stuck!
As per the title I'm trying to return an array that is built up as the function loops through. I want to only return the array variable on the else however it will not co-operate. It simply returns as blank away from the function, however within the else I can print_r it and shows as expected. It just simply won't return the array in the $open_array variable. Any ideas (or abuse) would be greatfully appreciated!
function find_parent($number, $open = false) {
if(isset($other_variable[$number])) {
foreach($other_variable[$number] as $val) {
$open[$val->id] = [$val->id;
$open = find_parent([$val->id, $open);
}
}
else {
return $open;
}
}
$open_array = find_parent($number);
print_r($open_array);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在“then”部分,您分配给 $open,但随后永远不会返回该值。因此,你不能真正期望得到任何东西,除非你输入了 else 部分,但它是一个未更改的版本。
所以这就是我要做的:我会选择一个不返回 $open 的版本。
在调用该函数之前初始化 $open。
传递下去。
然后根据需要进行修改。
没有理由真正返回这个 $open 值,因为无论如何你都是通过引用传递它的,即它应该始终是你正在操作的同一个对象(在那些情况下,它不是,它可能是一个错误) 。
这样,您可以专注于调用和返回的流程逻辑,并确保始终与相同的数据结构通信。
更新
In the "then" part, you assign to $open, but then never return that value. So you can't really expect to ever get something back, except in those cases where you enter the else part, but then it's an unchanged version.
So here's what I'd do: I'd go with a version without returning $open ever.
Initialize $open before you call the function.
Pass it on.
Then modify it where necessary.
There's no reason really to return this $open value since you're passing it on by reference anyway, i.e. it should always be the same object which you're manipulating (and in those cases that it isn't, it's probably a bug).
This way, you can concentrate on the flow logic with your calls and returns, and be sure you always talk to the same datastructure.
update