Answer the question
In order to leave comments, you need to log in
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" : "",//Вот эти данные нужно получить.
}
],
}
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;
}
Answer the question
In order to leave comments, you need to log in
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);
}
$tree = $model->getAllCategories();
return $this->render('profile', ['tree' => $tree]);
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>';
}
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 questionAsk a Question
731 491 924 answers to any question