0

Using CActiveRecord my table looks like this:

A column parent_id has relation many to id, and it works properly.

id | parent_id
---+----------
1    1      <- top
2    1      <- means parent_id with 1 has parent with id=1
3    1
4    2      <- parent for is id=2
5    2
6    2      and so many nested levels....

A goal is how to properly get nested as PHP classically way nested arrays data (arrays inside arrays). array(1,1) { array(2,1) { array(4,2) .... } }

Problem is Yii. I didn't find properly way how to pick up a data as nested array using properly CActiveRecord.

What is best way to make nested array results? A main goal is to easy forward to render view so I don't separate with too many functions and calling many models outside from modules or models.

A good is one function to get a result.

7
  • there is a nested set extension for Yii 1.1 and Yii 2 . Commented Jun 23, 2014 at 18:59
  • yiiframework.com/extension/nestedsetbehavior ? Commented Jun 23, 2014 at 19:02
  • Is there someone tried useful example on nested levels with same table? Commented Jun 23, 2014 at 19:04
  • @Marin Sagovac, please post all your depending GII generated models, ill help you out. Commented Jun 23, 2014 at 19:06
  • 1
    Iam sure, this will help you: stackoverflow.com/questions/8587341/… Cheers! Commented Jun 23, 2014 at 19:56

1 Answer 1

0

Solved using this: Recursive function to generate multidimensional array from database result

You need get a data as arrays from model:

$somemodel = MyModel::model()->findAll();

Then put all in array rather then Yii objects model or what you need:

foreach ($somemodel as $k => $v)
{
   $arrays[$k] = array('id' => $v->id, 'parent_id' => $v->parent_id, 'somedata' => 'Your data');
}

Then call a function:

function buildTree(array $elements, $parentId = 0) {
    $branch = array();

    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = buildTree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }

    return $branch;
}

Then call put all $arrays data into buildTree function to rebuild nesting arrays data.

$tree = buildTree($arrays);

Now your $tree is nested arrays data.

Note: there aren't depth into function but in convient way you can add using like this sample: Create nested list from Multidimensional Array

Sign up to request clarification or add additional context in comments.

Comments

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.