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.

Marin Sagovac
  • 3,932
  • 5
  • 23
  • 53

1 Answers1

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

Community
  • 1
  • 1
Marin Sagovac
  • 3,932
  • 5
  • 23
  • 53