Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How I can flatten a tree in an orderly way?

I have PHP array (tree), something like this:

$categoryTree = [
    0 => [
        'id' => 1360,
        'parent' => 0,
        'name' => 'main A',
        'children' => [
            0 => [
                'id' => 1361,
                'parent' => 1360,
                'name' => 'sub a1'
            ],
            1 => [
                'id' => 57,
                'parent' => 1360,
                'name' => 'sub a2'
            ]
        ]
    ],
    1 => [
        'id' => 10,
        'parent' => 0,
        'name' => 'Main B'
    ]
];

I want to convert it into:

$categoryTree = [
    0 => [
        'id' => 1360,
        'parent' => 0,
        'name' => 'main A'
    ],
    1 => [
        'id' => 1361,
        'parent' => 1360,
        'name' => 'sub a1'
    ],
    2 => [
        'id' => 57,
        'parent' => 1360,
        'name' => 'sub a2'
    ],
    3 => [
        'id' => 10,
        'parent' => 0,
        'name' => 'Main B'
    ]
];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is rather simple. You walk recursively and only make a recursive call if the node has the key children. During the iteration in the foreach loop, keep collecting results in an result array.

<?php

function flatten($tree, &$results){
    foreach($tree as $kid){
        $kid_copy = $kid;
        unset($kid_copy['children']);
        $results[] = $kid_copy;
        if(isset($kid['children'])) flatten($kid['children'], $results);
    }
}

Online Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading