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);
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
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);
return $open; // INSERTED
}
}
else {
return $open;
}
}
精彩评论