A
A
Alexander Sharomet2017-03-31 22:26:59
PHP
Alexander Sharomet, 2017-03-31 22:26:59

How to get recursion correctly?

I have a multidimensional array and I want to receive data regardless of nesting level.
example I need to get data by id.

public function getChildById($arr, $id) {
    if(is_array($arr)){
      foreach ($arr as $key => $value) {
        if($value['_id'] == $id){
          return $value;
        }else {
          if($this -> getChildById($value['childs'], $id) != null){
            print_r(1);
            return $arr[$key]['childs'][0];
          }
        }
      }
    }
    return  false;
  }

but I get maximum second level data.
how to solve it. thank.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Burov, 2017-03-31
@sharomet

if($this->getChildById($value['childs'], $id) != null){
    print_r(1);
    return $arr[$key]['childs'][0];
}

change to
if ($r = $this->getChildById($value['childs'], $id) !== false) {
    return $r;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question