Как создать путь на основе массива с несколькими дочерними элементами - PullRequest
0 голосов
/ 21 октября 2019

Итак, в основном я пытаюсь получить комбинации дочерних элементов массива, например, я получил массив:

[
"name" => "Item1", 
"children" => 
        [
        "name" => "Item2",
        "children" => [
                ["name" => "Item3"],
                ["name" => "Item4"]
                ]
        ],
        ["name" => "Item5"]
];

Я пытался работать с некоторыми функциями, которые я получил в stackoverflow,но я только заставил его работать со всеми сразу, я получал только

[
"Item4" => "Item1/Item2/Item4",
"Item5" => "Item1/Item5"
];

Вывод должен быть

[
"Item1" => "Item1",
"Item2" => "Item1/Item2",
"Item3" => "Item1/Item2/Item3"
"Item4" => "Item1/Item2/Item4"
"Item5" => "Item1/Item5"
];

Как я и просил, функция, с которой я работал раньше:

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

    return $lst;
}

1 Ответ

1 голос
/ 21 октября 2019

Мне пришлось исправить данные, так как уровни данных не совпадают. Остальной код является новым, так как я нашел так много ошибок в вашем существующем коде.

Комментарии в коде ...

$data = [
    "name" => "Item1",
    "children" =>
    [[
        "name" => "Item2",
        "children" =>[
        ["name" => "Item3"],
        ["name" => "Item4"]]
    ],
    ["name" => "Item5"]]
];

print_r(flatten($data));

function flatten($arr, $pathSoFar = '') {
    $lst = [];
    $path = $pathSoFar."/";
    foreach ( $arr as $key => $value )  {
        if ( $key === 'name' )   {
            // Add name of current level onto path
            $path .= $value;
            $lst[$value] = $path;
        }
        else if ( $key === 'children' )  {
            //Process child elements recursively and add into current array
            $lst = array_merge($lst, flatten($value, $path));
        }
        else    {
            // This is for sub-elements which probably are (for example) 0, 1
            // (removing trailing / to stop multiples)
            $lst = array_merge($lst, flatten($value, rtrim($path,"/")));
        }
    }
    return $lst;
}
...