0
votes

I have a tree array from cakephp 2.0 tree behavior noe i need to separate it in levels so i can build a selector per each level. Here is an example of the array:

Array
(
    [25] => Global
    [26] => _Region1
    [29] => __Pais1
    [41] => ___Distrito1
    [42] => ___Distrito2
    [30] => __Pais2
    [43] => ___Distrito1
    [44] => ___Distrito2
    [31] => __Pais3
    [45] => ___Distrito1
    [32] => __Pais4
    [46] => ___Distrito1
    [27] => _Region2
    [33] => __Pais1
    [47] => ___Distrito1
    [34] => __Pais2
    [48] => ___Distrito1
    [35] => __Pais3
    [36] => __Pais4
    [28] => _Region3
    [37] => __Pais1
    [38] => __Pais2
    [39] => __Pais3
    [40] => __Pais4
)

Now what i need is to create one select for global, another select for region1 another for pais1 and another for disctrito1

The problem is that i can use ids to generate it since this will be changing by the user.

What will be the best way to manipulate this array so it builds a select to each level of the array.

Thanks in advance.

1

1 Answers

3
votes

You can get the tree as a nested array via find('threaded'). This will give you each item in the tree, with a 'children' key containing all child nodes as an array;

Retrieving Your Data - find('threaded')

However, as indicated, because the content will be modified by the user, the depth of the tree may change. To accommodate for those changes, you'll need to use a 'recursive function' to loop through the tree, regardless of its depth

Mockup Code:

echo $this->MyTreeHelper->buildTreeDropDowns($treeData);


class MyTreeHelper extends AppHelper {

    public function buildTreeDropDowns($treeData)
    {
         $output = '';

         foreach($treeData as $item) {
              $output .= createAdropDown($item);

              if (!empty($item['children'])) {
                   $output .= $this->buildTreeDropDowns($item['children']);
              }
         }
         return $output;
    }
}