odannyc/treeize

终极树库。满足您所有树递归需求。

v1.2.2 2016-12-15 19:54 UTC

This package is auto-updated.

Last update: 2024-09-07 05:21:25 UTC


README

终极树库。满足您所有树递归需求。

Treeize::create($tree)->parse()->get();

安装

您可以使用composer安装此库

composer require odannyc/treeize

使用

给定一个简单的数组

$tree = [
  [
    "id" => 1,
    "parent_id" => 0
  ],
  [
    "id" => 2,
    "parent_id" => 1
  ],
  [
    "id" => 3,
    "parent_id" => 1
  ],
  [
    "id" => 4,
    "parent_id" => 2
  ],
  [
    "id" => 5,
    "parent_id" => 2
  ],[
    "id" => 6,
    "parent_id" => 0
  ],
  [
    "id" => 7,
    "parent_id" => 6
  ],
  [
    "id" => 8,
    "parent_id" => 6
  ]
]

您将能够解析此树并正确递归地设置它,方法如下

Treeize::create($tree)->parse()->get();

输出将是

[
  [
    "id" => 1,
    "parent_id" => 0,
    "children" => [
      [
        "id" => 2,
        "parent_id" => 1,
        "children" => [
          [
            "id" => 4,
            "parent_id" => 2
          ],
          [
            "id" => 5,
            "parent_id" => 2
          ]
        ]
      ],
      [
        "id" => 3,
        "parent_id" => 1
      ],
    ]
  ],
  [
    "id" => 6,
    "parent_id" => 0,
    "children" => [
      [
        "id" => 7,
        "parent_id" => 6
      ],
      [
        "id" => 8,
        "parent_id" => 6
      ]
    ]
  ]
]

如果您想将“children”键更改为任何其他字符串,您可以在解析之前通过链式调用create方法来实现。所以

Treeize::create($tree)->childrenKey('nodes')->parse()->get();

还有其他选项可以链式调用该方法,以下是完整列表

Treeize::create($tree)
  ->parentKey('pid')
  ->indexKey('id')
  ->parentId(0)
  ->childrenKey('nodes')
  ->parse(function($item) {//do stuff to item})
  ->get();

parentKey

  • 设置父键名称:默认为"parent_key"

indexKey

  • 设置索引键名称:默认为"id"

parentId

  • 设置初始父ID以搜索:如果没有提供,则自动计算

childrenKey

  • 设置子键名称,如上所述。

parse

  • 接受一个回调函数,您可以将其应用于树中的每个项目,在此实例中,项目是一个数组。