Построить массив php на основе потомков из многомерного массива - PullRequest
0 голосов
/ 31 октября 2018

У меня есть массив 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",
)

Здесь мне нужно взять «текст» и затем добавить «/», затем пройти «дети», чтобы взять их текст. Текст от детей будет добавлен вместе с родительским.

Ответы [ 2 ]

0 голосов
/ 31 октября 2018

Я смог сделать это с 3-мя вложенными циклами.

//initialize new array to hold newly generated strings
$new_array = [];

foreach($arr as &$value) {
    //loop through first set

    foreach($value['children'] as $child) {

        //loop through children, create a string that contains the first set of values "text", and the childrens "text"
        $string = "{$value['text']}/{$child['text']}";

        foreach($child['children'] as $child2) {

            //loop through each child of child1 and add a new string to the new_array containing `$string` + the child2.
            $new_array[] = $string .= "/{$child2['text']}"; 

        }
    }

}

Выход:

Array ( [0] => eventyrer/news/a [1] => eventyrer/nyheter/b [2] => eventyrer2017/news/c [3] => eventyrer2017/nyheter/d )
0 голосов
/ 31 октября 2018

Следующий код пытается рекурсивный подход и добавляет каждый сегмент text для каждого child в 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
)
...