一个简单的辅助包,允许在PHP中使用树结构

1.0.0 2018-04-05 14:55 UTC

This package is auto-updated.

Last update: 2024-09-05 06:25:20 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

快速安装

composer require danielcosta/tree

使用方法

要使用,只需获取以下类似的数组

$flatArray = [
    [
        'id' => 1,
        'name' => 'Level 1',
        'parentId' => 0,
        'nodes' => [],
    ],
    [
        'id' => 3,
        'name' => 'Level 3',
        'parentId' => 2,
        'nodes' => [],
    ],
    [
        'id' => 2,
        'name' => 'Level 2',
        'parentId' => 1,
        'nodes' => [],
    ],
];

并将它传递给辅助函数 Tree,使用 Tree::makeFromFlatArray($flatArray);。结果将正好是这样

$result = Tree::makeFromFlatArray($flatArray);
print_r($result);
/*
Array
(
    [id] => 1
    [name] => Level 1
    [parentId] => 0
    [nodes] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [name] => Level 2
                    [parentId] => 1
                    [nodes] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 3
                                    [name] => Level 3
                                    [parentId] => 2
                                    [nodes] => Array
                                        (
                                        )
                                )
                        )
                )
        )
)
*/

此方法的可选参数包括

  • $parentId = 0 - 当你想设置返回的第一级时
  • string $key = 'id' - 你的扁平数组中的主键
  • string $parentKey = 'parentId' - 你的扁平数组中的父键
  • string $childKey = 'nodes' - 存储子节点的位置

请给我买杯咖啡

paypal