Skip to content
Advertisement

How do I format Nested Set Model data into an array?

Let’s dig in the main problem right away, I have the input like this

$category = array(
  'A' => array('left' => 1, 'right' => 8),
  'B' => array('left' => 2, 'right' => 3),
  'C' => array('left' => 4, 'right' => 7),
  'D' => array('left' => 5, 'right' => 6),
  'E' => array('left' => 9, 'right' => 10),
);

I want the output to be something like this

$tree = array(
  array('A', 'B'),
  array('A', 'C', 'D'),
  array('E'),
);

which one is the best and fast function to loop though the input array and create the output result like this ?

Advertisement

Answer

Working with a nested set is a perfect case for recursion.

Given your data:

$category = array(
    'A' => array('left' => 1, 'right' => 9),
    'B' => array('left' => 2, 'right' => 4),
    'C' => array('left' => 5, 'right' => 8),
    'D' => array('left' => 6, 'right' => 7),
    'E' => array('left' => 10, 'right' => 11),
);

The following will break your nested set data down into a properly nested array in PHP:

function createTree($category, $left = 0, $right = null) {
    $tree = array();
    foreach ($category as $cat => $range) {
        if ($range['left'] == $left + 1 && (is_null($right) || $range['right'] < $right)) {
            $tree[$cat] = createTree($category, $range['left'], $range['right']);
            $left = $range['right'];
        }
    }
    return $tree;
}

$tree = createTree($category);
print_r($tree);

Output:

Array
(
    [A] => Array
        (
            [B] => Array
                (
                )

            [C] => Array
                (
                    [D] => Array
                        (
                        )

                )

        )

    [E] => Array
        (
        )

)

Then you can flatten your proper tree into the format you want with the following:

function flattenTree($tree, $parent_tree = array()) {
    $out = array();
    foreach ($tree as $key => $children) {
        $new_tree = $parent_tree;
        $new_tree[] = $key;
        if (count($children)) {
             $child_trees = flattenTree($children, $new_tree);
            foreach ($child_trees as $tree) {
                $out[] = $tree;
            }
        } else {
            $out[] = $new_tree;
        }
    }
    return $out;
}

$tree = flattenTree($tree);
print_r($tree);

Output:

Array
(
    [0] => Array
        (
            [0] => A
            [1] => B
        )

    [1] => Array
        (
            [0] => A
            [1] => C
            [2] => D
        )

    [2] => Array
        (
            [0] => E
        )

)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement