PHP code example of rgilyov / array-tree-walker

1. Go to this page and download the library: Download rgilyov/array-tree-walker library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rgilyov / array-tree-walker example snippets


composer 

$tree = [
    'name'    => 'child',
    'parents' => [
        'mother' => [
            'name'    => 'mother',
            'parents' => [
                'mother' => [
                    'name' => 'first grand mother'
                ],
                'father' => [
                    'name' => 'first grand father'
                ]
            ]
        ],
        'father' => [
            'name'    => 'father',
            'parents' => [
                'mother' => [
                    'name' => 'second grand mother'
                ],
                'father' => [
                    'name'    => 'second grand father',
                    'parents' => [
                        'mother' => [
                            'name' => 'second grand grand mother'
                        ]
                    ]
                ]
            ]
        ]
    ]
];

$walker = new \RGilyov\ArrayTreeWalker($tree);

echo $walker->parents->mother->parents->father->get('name'); // result: `first grand father`

echo $walker->parents->mother->parents->father['name']; // result: `first grand father`

echo $walker->parents->mother->parents->father->name['name']; // result: `first grand father`

echo $walker->parents->mother->parents->father->name->father['name']; // result: null

$walkerWithNodeName = new \RGilyov\ArrayTreeWalker($tree, 'parents');

echo $walkerWithNodeName->father->father->get('name'); // result: `second grand father`

echo $walkerWithNodeName->father->father->mother['name']; // result: 'second grand grand mother'

echo $walkerWithNodeName->father->father->mother->mother['name']; // result: null


$walker = new \RGilyov\ArrayTreeWalker($tree, 'parents');

/*
 * If an array will be returned the values for given keys will be rewritten
   and if keys didn't exist in the node they will be attached
 */
$walker->walkDown(function ($node, $level, $nodeNumber, $parentNodeNumber) {

    return [
        'level' => $level,
        'node_number' => $nodeNumber,
        'parent_node_number' => $parentNodeNumber
    ];

});

$walker->walkUp(function ($node, $nodeChildren, $parameters, $level, $nodeNumber) {

    return [
        'super_name' => $node['name'] . ' ' . implode(array_map(function ($child) {
            return $child['name'];
        }, $nodeChildren), ' ')
    ];

});


$walker->toArray();
$walker->count();
$walker->offsetExists('key');
$walker->offsetUnset('key');
$walker->offsetGet('key');
$walker->offsetSet('key', 'value');