php - 使用递归函数使用php数组为树结构数据创建json数据

标签 php mysql json yii

我有类别表:

CategoryID    CategoryName   ParentID
     1           Root          Null
     2           News            1
     3           Horoscope       1
     4           Sports          2
     5           National        2
     6           Daily           3
     7           Aries           6
     8           Weekly          3
     9           Aries           8

我正在尝试创建树结构的 json 数据,如下所示:

[{
    "id":1,
    "text":"Root",
    "children":[{
        "id":2,
        "text":"News",
        "state":"closed",
        "children":[{
            "id":4,
            "text":"Sports"
        },{
            "id":5,
            "text":"National"
        }]
    },{
        "id":3,
        "text":"Horoscope",
        "children":[{
            "id":6,
            "text":"Daily",
                        "children":[{
                  "id":7,
                  "text":"Aries"
                  }],

         },{
            "id":8,
            "text":"Weekly",
                        "children":[{
                  "id":9,
                  "text":"Aries"
                  }],
            }
        }]
}]

我有以下功能来呈现所有类别和子类别

   public function categoryData($parent)
    {                 
        $model=new Category();
        $cat=$model->findAllByAttributes(array('ParentCategoryID'=>$parent,'Status'=>2));

        $category = array();


        foreach($cat as $record) 
        {
          global $category;
          $category['id'][$record->CategoryID] = $record->CategoryID;
          $category['text'][$record->CategoryID] = $record->CategoryName;


          // $category['children'][$record->CategoryID] = array();

          //$names[] = $record->CategoryName;

          $this->categoryData($record->CategoryID);

        }
        //array_push($category['children'][$record->ParentCategoryID], $category['children'][$record->CategoryID]);
        return $category;
    }

问题: 但是上面的操作没有以正确的格式将类别放在数组中,因此我可以通过应用 json_encode($category) 函数创建上面的 json 数据格式。

如何使用递归函数将类别数据放置在树结构数组中?

最佳答案

public $children = array() 属性添加到您的 Category 模型。然后遍历结果并在父级的 $children 数组中设置一个引用:

$categories = Category::model()->findAll(array('index'=>'id'));
foreach($categories as $category)
    $categories[ $category->id_parent ]->children[] = $category;

echo json_encode($categories);

关于php - 使用递归函数使用php数组为树结构数据创建json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16120892/

相关文章:

sql - MySQL解释计划中 "Select tables optimized away"的含义

mysql - 获取触发器的插入变量

php - Microsoft Dynamics CRM 和 PHP/JSON

json - 将 autodesk .dwg 和 .dwf 文件转换为 Three.js json 格式

php - 将 JOIN SQL 查询序列化为 JSON 的最佳方法

php - IPN 如何将用户用户名添加到 Paypal 交易 (PHP)

php - 如何在 Redhat/Centos 中为 Apache 添加 PHP 模块?

mysql - 如何在一列SQL中存储多个值

php - 如何在 PHP 中使用正则表达式匹配固定数量的数字?

php - Facebook 登录 Api : unable to get email in php