1

I have a class called Member. I am trying to add a multidimensional array as a property like so:

class Member {

public $name;
public $inheritingMembers;

public function __construct($name, $family) {
    $this->name = $name;
    $this->inheritingMembers = $this->findInheritingMembers($family, $name);
}

function findInheritingMembers($array, $keySearch) {
    foreach ($array as $key => $item){
        if ($key == $keySearch){
            return $item['children'];
        } else {
            if (is_array($item))
                $this->findInheritingMembers($item, $keySearch);
        }
    }
    return false;
}

}

The function "findInherititngMembers" returns a multidimensional array which I can see with var_dump(). The problem is, I cannot seem to assign this array as the inheritingMembers property of the Member object.

3
  • return $this->findInheritingMembers($item, $keySearch);. Commented Aug 25, 2015 at 17:18
  • The array is returning correctly. The problem is assigning it to the property in the constructor. Commented Aug 25, 2015 at 17:24
  • I tested this and it seems you do need to return $this->findInheritingMembers($item, $keySearch). You are saying it isn't assigning correctly. What does var_dump($this->inheritingMembers) give you after you've made a new instance? Commented Aug 25, 2015 at 19:02

1 Answer 1

0

I think you need another return in your recursive function:

function findInheritingMembers($array, $keySearch) {
    foreach ($array as $key => $item){
        if ($key == $keySearch){
            return $item['children'];
        } else {
            if (is_array($item))
                return $this->findInheritingMembers($item, $keySearch);
        }
    }
    return false;
}
Sign up to request clarification or add additional context in comments.

3 Comments

The array is returning correctly. The problem is assigning it to the property in the constructor.
@OllyTenerife: Yeah, but if you get one level deeper (in the else block) you are not returning anything at all. Is this the desired output? Have you tried my approach?
Yes, I see what you mean, if it doesn't match the first key it immediately goes one level deeper into the sub-array, without iterating over the others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.