vhood/tree-converter

tree structure type switcher

1.0.0 2022-07-11 05:41 UTC

This package is auto-updated.

Last update: 2022-10-03 13:26:56 UTC


README

tests version downloads license

This package based on native php arrays allows you to switch a tree type.

Supported types:

  • Adjacency list
  • Materialized path
  • Nested set
  • Associative array trees

See data examples

Installation

composer require vhood/tree-converter

Requirements

  • php >=5.6

Usage

Usage example:

use Vhood\TreeType\Converter;
use Vhood\TreeType\Type\AdjacencyList;

$adjacencyList = [
    [
        'id' => 1,
        'name' => 'node1',
        'parent_id' => null,
    ],
    [
        'id' => 2,
        'name' => 'node2',
        'parent_id' => 1,
    ],
];

$adjacencyListConverter = new Converter(new AdjacencyList($adjacencyList));

print_r($adjacencyListConverter->toAssociativeArrayTree('children', 'id'));

// Array
// (
//     [0] => Array
//         (
//             [id] => 1
//             [name] => node1
//             [children] => Array
//                 (
//                     [0] => Array
//                         (
//                             [id] => 2
//                             [name] => node2
//                             [children] => Array
//                                 (
//                                 )

//                         )

//                 )

//         )

// )

See all types

Extra functionality

Materialized path level calculation example:

use Vhood\TreeType\Converter;
use Vhood\TreeType\Type\MaterializedPath;

$materializedPath = [
    [
        'name' => 'node1',
        'path' => '/1/',
    ],
    [
        'name' => 'node2',
        'path' => '/1/2/',
    ],
];

$materializedPathConverter = new Converter(new MaterializedPath($materializedPath));

print_r($materializedPathConverter->toMaterializedPath('path', '/', 'level'));

// Array
// (
//     [0] => Array
//         (
//             [name] => node1
//             [path] => /1/
//             [level] => 1
//         )

//     [1] => Array
//         (
//             [name] => node2
//             [path] => /1/2/
//             [level] => 2
//         )

// )

Other features:

  • nodes identification
  • keys renaming
  • keys removing

See the converting interface

History