A
A
Alexander Sharomet2017-03-30 13:27:24
PHP
Alexander Sharomet, 2017-03-30 13:27:24

How to get data using recursion?

Tell me how to display subcategories correctly using a recursive function?
I am passing this array to the method.

{
    "_id" : ObjectId("18b97aa654bce61356002559"),
    "name" : "Photo",
    "childs" : [ 
        {
            "_id" : "22b55aa654bce61356002559",//Вот эти данные нужно получить.
            "name" : "Photo childs", //Вот эти данные нужно получить.
            "childs" : "",//Вот эти данные нужно получить.
        }
    ],
}

I need to get the data of all subcategories. There can be an infinite number of categories.
public function getChildById($arr, $id) {

  if(is_array($arr)){
        
    if((string)$arr['_id'] == $id){
        return $arr;
      }else {
        foreach ($arr as $kay => $value) {
          $this -> getChildById($value['childs'][$kay], $id);
              }
    }
  }
  return  false;
}

But in the end, the method returns nothing.
Where did I go wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Victor Umansky, 2017-03-30
@sharomet


In the category model, I made a public $childs virtual property ;
in the model

/**
     * Строим дерево категории
     *
     * @param $data
     * @param int $rootID
     * @return array
     */
    protected function buildTree($data, $rootID = 0)
    {
        $tree = [];
        foreach ($data as $id => $node) {
            if ($node['parent_id'] == $rootID) {
                unset($data[$id]);
                $node['childs'] = $this->buildTree($data, $node['id']);
                $tree[] = $node;
            }
        }
        return $tree;
    }

    /**
     * Получаю все категории
     *
     * @return array
     */
    public function getAllCategories()
    {
        $data = Category::find()->asArray()->all();
        return $this->buildTree($data);
    }

in controller
$tree = $model->getAllCategories();
return $this->render('profile', ['tree' => $tree]);

in view
foreach ($tree as $cat) {
// root 1-й уровень
    echo $cat['title'];
    if ($cat['childs'] > 0) {
        foreach ($cat['childs'] as $childs) {
// category 2-й уровень
            if (empty($childs['childs'])) {
                echo  $childs['title'];
            } else {
                echo '<b><br/>' . $childs['title'] . '</b><br/>';
            }
            foreach ($childs['childs'] as $child) {
// category 3-й уровень
                echo $child['title'];
            }
        }
    }
    echo '</div>';
}

A
Alexander Sharomet, 2017-03-30
@sharomet

Solution for any level)

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question