获取所选元素及其子阵列

问题描述 投票:0回答:1

我有由外部系统以下面的格式返回的数组的一个php阵列

$elements = [
    [
        'id' => 1,
        'name' => 'Element 1',
        'parent_id' => 0
    ],
    [
        'id' => 2,
        'name' => 'Element 2',
        'parent_id' => 0
    ],
    [
        'id' => 3,
        'name' => 'Element 3',
        'parent_id' => 1
    ],
    [
        'id' => 4,
        'name' => 'Element 4',
        'parent_id' => 1
    ],
    [
        'id' => 5,
        'name' => 'Element 5',
        'parent_id' => 1
    ],
    [
        'id' => 6,
        'name' => 'Element 6',
        'parent_id' => 2
    ],
    [
        'id' => 7,
        'name' => 'Element 7',
        'parent_id' => 2
    ],
    [
        'id' => 8,
        'name' => 'Element 8',
        'parent_id' => 3
    ],
    [
        'id' => 9,
        'name' => 'Element 9',
        'parent_id' => 3
    ],
    [
        'id' => 10,
        'name' => 'Element 10',
        'parent_id' => 3
    ]
];

如果有帮助,这种结构中,“翻译”一棵树应该是这样的:

  • 元1 3元 8元 要素9 10元 元4 5元
  • 元素2 6元 要素7

我现在需要做的是:对于IDS的一个给定的列表,返回所有与所提供的ID和其子元素(不管多少级)。例如,如果我接收与[2, 3]阵列输出应为[2, 3, 7, 8, 9, 10]

我创建了一个功能,基于阵列上的树结构:

    public function createTree($parent = 0)
    {
        // This returns all the direct children of $parent
        $elements = filterByParent($parent); 
        $categories = [];
        $i = 0;
        foreach ($elements as $element) {
            $categories[$i] = $element;
            $categories[$i]['children'] = createTree($element['id']);
            $i++;
        }

        return $categories;
    }

但我不知道现在该怎么继续。

任何帮助,将不胜感激。

提前致谢!

php arrays tree
1个回答
1
投票

我已经改变了方法,因为它是很容易从一个单一的递归方法创建一个列表。这也通过在$elements,以便它可以容易地测试。

该方法可采取任意的ID或ID的数组,如果它是一个单一的ID,然后它使一个阵列,以便它可以在列表上foreach()。然后,它只是检查它针对每一个元素,并添加到工作清单此。然后调用同样的方法可以找到更多的子项。

function dependants ( $ids, $elements )  {
    if ( !is_array($ids) )   {
        $ids = [$ids];
    }
    $deps = $ids;
    foreach ( $ids as $id ) {
        foreach ( $elements as $element )   {
            if ( $element['parent_id'] == $id ) {
                $deps = array_merge($deps, dependants($element['id'], $elements));
            }
        }
    }
    return $deps;
}
print_r(dependants([2,3], $elements ));

Array
(
    [0] => 2
    [1] => 3
    [2] => 6
    [3] => 7
    [4] => 8
    [5] => 9
    [6] => 10
)
© www.soinside.com 2019 - 2024. All rights reserved.