如何“展平”未知深度和长度的多维数组并记录其父子关系?

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

我有一个看起来像这样的PHP数组:

Array
(
    [0] => Array
        (
            [id] => 2
            [name] => Item2
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [name] => Item1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 5
                                            [name] => Item5
                                        )
                                )
                        )
                    [1] => Array
                        (
                            [id] => 4
                            [name] => Item4
                        )
                )
        )
    [1] => Array
        (
            [id] => 3
            [name] => Item3
        )
)

具有未知(不可预测)的深度和长度。任何级别的任何项目[[可能有,也可能没有孩子。它是通过包含产品组的xml文件创建的。我想将其转换为包含三个元素的数组的数组:id,name和parent id:

[0] => array('id' => '2', 'name' => 'Item2', 'parent' => 0), [1] => array('id' => '1', 'name' => 'Item1', 'parent' => 2), [2] => array('id' => '4', 'name' => 'Item4', 'parent' => 2) etc.
我该怎么办?谢谢!
php arrays multidimensional-array flatten
1个回答
1
投票
function list_items($array, $parent = 0) { $output = array(); foreach ($array as $arr) { $output[] = array('id' => $arr['id'], 'name' => $arr['name'], 'parent' => $parent); if (is_array($arr['children'] ?? NULL)) { $output = array_merge($output, list_items($arr['children'], $arr['id'])); } } return $output; } $items = list_items($array);

输出(用于我稍微扩展的数据:

Array
(
    [0] => Array
        (
            [id] => 2
            [name] => Item2
            [parent] => 0
        )
    [1] => Array
        (
            [id] => 1
            [name] => Item1
            [parent] => 2
        )
    [2] => Array
        (
            [id] => 5
            [name] => Item5
            [parent] => 1
        )
    [3] => Array
        (
            [id] => 4
            [name] => Item4
            [parent] => 2
        )
    [4] => Array
        (
            [id] => 3
            [name] => Item3
            [parent] => 0
        )
)

Demo on 3v4l.org

更新

事实证明,数组结构不一致;当只有一个孩子时,仅存储孩子值,而不是单个元素数组。这可以通过检查数组以查看是否设置了idИд)元素来解决,如果已设置,则在处理之前将数组更深一层:

function list_items($array, $parent = 0) { $output = array(); if (isset($array['Ид'])) { $array = array($array); } foreach ($array as $arr) { if (!is_array($arr)) echo $arr; $output[] = array('id' => $arr['Ид'], 'name' => $arr['Наименование'], 'parent' => $parent); if (is_array($arr['Группы']['Группа'] ?? NULL)) { $output = array_merge($output, list_items($arr['Группы']['Группа'], $arr['Ид'])); } } return $output; } $items = list_items($array); print_r($items);

Demo on 3v4l.org

© www.soinside.com 2019 - 2024. All rights reserved.