【问题标题】:best way to handle a tree array处理树数组的最佳方法
【发布时间】:2013-04-13 02:25:01
【问题描述】:

我有一个来自 cakephp 2.0 树行为的树数组,我需要将它分成多个级别,这样我就可以为每个级别构建一个选择器。下面是数组的一个例子:

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
)

现在我需要为全局创建一个选择,为 region1 创建另一个选择,为 pais1 创建另一个选择,为 disctrito1 创建另一个选择

问题是我可以使用 ids 来生成它,因为这将由用户更改。

操作此数组的最佳方法是什么,以便它为数组的每个级别构建一个选择。

提前致谢。

【问题讨论】:

    标签: php arrays cakephp tree


    【解决方案1】:

    您可以通过find('threaded') 将树作为嵌套数组获取。这将为您提供树中的每个项目,并带有一个包含所有子节点作为数组的“子”键;

    Retrieving Your Data - find('threaded')

    但是,如前所述,由于内容将由用户修改,因此树的深度可能会发生变化。为了适应这些变化,您需要使用 '递归函数' 循环遍历树,无论其深度如何

    样机代码:

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多