How to return an element of array, which finded by recursion?

So, i have a little trouble: I have a class, let's name it "Menu", also, i have an array, which provides an elements for "Menu", it looks like that

class Menu {
    private $_data = [];
    public function __construct() {
            $this->_data = array(
                "Parent1" => array(
                    "Child1" => array(
                        "id" => 1,
                        "minQuantity" => x,
                        "maxQuantity" => x,
                        "cost" => x,
                    ),
                    "Child2"...
                ),
                "ParentX" => array(
                    "ChildXX"...
                )
                /* AND SO ON */
            );
    }
}

Also, in "Menu" i have a function, which by recursion try to find an element of the $this->_data with specified value, function looks like that:

public function findChildById($parent = null, $id = null) {
    foreach ($parent as $_parent => $_child) {
        if (array_key_exists($id, $parent)) var_dump($parent);   
        if (is_array($_child)) $this->findChildById($_child, $id); 
    }
}

But, when it finds needed element, and I try to return it - result is always NULL. Using var_dump leads to obvious output, I can see what exactly what I need, but i cant return an element from function. What should i do?

Upvotes: 0

Views: 68

Answers (1)

jh1711
jh1711

Reputation: 2328

Since you only try to find one element, it should be enough to pass the return value up the recursion stack. E.g. like this:

public function findChildById($parent = null, $id = null) {
  foreach ($parent as $_parent => $_child) {
    if (array_key_exists($id, $parent)) return $parent; //first return  
    if (is_array($_child)) {
      $tmp = $this->findChildById($_child, $id); 
      if (!is_null($tmp)) return $tmp; //if a deeper step found sth. pass it up
    }
  }
}

The reason for the NULLs you get, must be, because PHP functions return NULL implicitly when the code does not reach a return statement.

Upvotes: 1

Related Questions