如何将嵌套集合模型数据格式化为数组? [英] How do I format Nested Set Model data into an array?

查看:88
本文介绍了如何将嵌套集合模型数据格式化为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们立即深入研究主要问题,我有这样的输入

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),
);

我希望输出是这样的

$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 ?

推荐答案

使用嵌套集是递归的完美案例.

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

提供您的数据:

$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),
);

以下内容将嵌套的集合数据分解为PHP中正确嵌套的数组:

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);

输出:

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);

输出:

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

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

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

)

这篇关于如何将嵌套集合模型数据格式化为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆