基于多维数组的子代构建php数组

Jyotirmoy比斯瓦斯

我有这样的PHP数组:

$arr = array(
    0 => array(
        "text" => "eventyrer",
        "children"=> array(
                4 => array(
                        "text" => "news",
                        "children"=> array(
                                1=> array("text"=>"a")
                            )
                    ),

                5 => array(
                        "text" => "nyheter",
                        "children"=> array(
                                1=> array("text"=>"b")
                            )
                    )
            ) 
    ),

    1 => array(
        "text" => "eventyrer2017",
        "children"=> array(
                6 => array(
                        "text" => "news",
                        "children"=> array(
                                1=> array("text"=>"c")
                            )
                    ),

                8 => array(
                        "text" => "nyheter",
                        "children"=> array(
                                1=> array("text"=>"d")
                            )
                    )
            ) 
    )

);

我如何获得这样的输出:

$array = array(
    0 => "eventyrer/news/a",
    1 => "eventyrer/nyheter/b",
    2 => "eventyrer2017/news/c",
    4 => "eventyrer2017/nyheter/d",
)

在这里,我需要获取“文本”,然后附加“ /”,然后遍历“子级”以获取其文本。来自子级的文本将与父级一起添加。

约翰

以下代码尝试使用递归方法,并textchildin中的每个段附加每个段children这样就可以使数据结构具有无限深度。

function flatten($arr) {
    $lst = [];
    /* Iterate over each item at the current level */
    foreach ($arr as $item) {
        /* Get the "prefix" of the URL */
        $prefix = $item['text'];
        /* Check if it has children */
        if (array_key_exists('children', $item)) {
            /* Get the suffixes recursively */
            $suffixes = flatten($item['children']);
            /* Add it to the current prefix */
            foreach($suffixes as $suffix) {
                $url = $prefix . '/' . $suffix;
                array_push($lst, $url);
            }
        } else {
            /* If there are no children, just add the 
             * current prefix to the list */
            array_push($lst, $prefix);
        }
    }

    return $lst;
}

输出

Array
(
    [0] => eventyrer/news/a
    [1] => eventyrer/nyheter/b
    [2] => eventyrer2017/news/c
    [3] => eventyrer2017/nyheter/d
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章