Использование рекурсии для выравнивания массива PHP с подэлементами, основанными на значениях (тратится на это час!) - PullRequest
0 голосов
/ 23 октября 2010

Я пытаюсь построить меню навигации.Я получаю массив с такой структурой:

[ 
  [
    Title = A
    Sub items = [
      Title = B
      Sub items = [
        Title = C
      ]
    ]
  ],
  [
    Title = A
    Sub items = [
      Title = B
      Sub items = [
        Title = D
      ]
    ]
  ],
]

Мне нужно взять его так, чтобы он выглядел так:

[
  Title = A
  Sub items = [
    Title = B
    Sub items = [
      Title = C,
      Title = D
    ]
  ]
]

Я перечислил свои входные данные и желаемый выводниже.Я рву свои волосы на этом.Я пытался использовать рекурсию, но у меня были некоторые проблемы с бесконечными циклами повсюду.Любая помощь по хорошему способу решения этой проблемы была бы очень признательна.

Ввод:

Array
(
    [0] => Array
        (
            [title] => Dashboard
            [path] => dashboard/
        )

    [1] => Array
        (
            [title] => Settings
            [path] => settings/
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Instances
                            [path] => settings/instances/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Add an Instance
                                            [path] => settings/instances/add-an-instance/
                                        )

                                )

                        )

                    [1] => Array
                        (
                            [title] => Modules
                            [path] => settings/modules/
                        )

                    [2] => Array
                        (
                            [title] => Administrator
                            [path] => settings/administrator/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Change Password
                                            [path] => settings/administrator/change-password/
                                        )

                                )

                        )

                )

        )

    [2] => Array
        (
            [title] => Settings
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Routes
                            [path] => modules/routes/settings/routes/
                        )

                )

        )

    [3] => Array
        (
            [title] => Settings
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Cookies
                            [path] => modules/cookies/settings/cookies/
                        )

                )

        )

    [4] => Array
        (
            [title] => Settings
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Sessions
                            [path] => modules/sessions/settings/sessions/
                        )

                )

        )

    [5] => Array
        (
            [title] => Settings
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Databases
                            [path] => modules/databases/settings/databases/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Add a Database
                                            [path] => modules/databases/settings/databases/add-a-database/
                                        )

                                )

                        )

                )

        )

    [6] => Array
        (
            [title] => Settings
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Models
                            [path] => modules/models/settings/models/
                        )

                )

        )

    [7] => Array
        (
            [title] => Settings
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Users and Accounts
                            [path] => modules/users-and-accounts/settings/users-and-accounts/
                        )

                )

        )

    [8] => Array
        (
            [title] => Users and Accounts
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Users
                            [path] => modules/users-and-accounts/users/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Add a User
                                            [path] => modules/users-and-accounts/users/add-a-user/
                                        )

                                )

                        )

                    [1] => Array
                        (
                            [title] => Accounts
                            [path] => modules/users-and-accounts/accounts/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Add an Account
                                            [path] => modules/users-and-accounts/accounts/add-an-account/
                                        )

                                    [1] => Array
                                        (
                                            [title] => Account Types
                                            [path] => modules/users-and-accounts/accounts/account-types/
                                            [subItems] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [title] => Add an Account Type
                                                            [path] => modules/users-and-accounts/accounts/account-types/add-an-account-type/
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

)

Вывод:

Array
(
    [0] => Array
        (
            [title] => Dashboard
            [path] => dashboard/
        )

    [1] => Array
        (
            [title] => Settings
            [path] => settings/
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Instances
                            [path] => settings/instances/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Add an Instance
                                            [path] => settings/instances/add-an-instance/
                                        )

                                )

                        )

                    [1] => Array
                        (
                            [title] => Modules
                            [path] => settings/modules/
                        )

                    [2] => Array
                        (
                            [title] => Administrator
                            [path] => settings/administrator/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Change Password
                                            [path] => settings/administrator/change-password/
                                        )

                                )

                        )

                    [3] => Array
                    (
                        [title] => Routes
                        [path] => modules/routes/settings/routes/
                    )

                    [4] => Array
                        (
                            [title] => Cookies
                            [path] => modules/cookies/settings/cookies/
                        )

                    [5] => Array
                    (
                        [title] => Sessions
                        [path] => modules/sessions/settings/sessions/
                    )

                    [6] => Array
                    (
                        [title] => Databases
                        [path] => modules/databases/settings/databases/
                        [subItems] => Array
                            (
                                [0] => Array
                                    (
                                        [title] => Add a Database
                                        [path] => modules/databases/settings/databases/add-a-database/
                                    )

                            )

                        )

                    [7] => Array
                    (
                        [title] => Models
                        [path] => modules/models/settings/models/
                    )

                    [8] => Array
                    (
                        [title] => Users and Accounts
                        [path] => modules/users-and-accounts/settings/users-and-accounts/
                    )
                )
        )
    [2] => Array
        (
            [title] => Users and Accounts
            [subItems] => Array
                (
                    [0] => Array
                        (
                            [title] => Users
                            [path] => modules/users-and-accounts/users/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Add a User
                                            [path] => modules/users-and-accounts/users/add-a-user/
                                        )

                                )

                        )

                    [1] => Array
                        (
                            [title] => Accounts
                            [path] => modules/users-and-accounts/accounts/
                            [subItems] => Array
                                (
                                    [0] => Array
                                        (
                                            [title] => Add an Account
                                            [path] => modules/users-and-accounts/accounts/add-an-account/
                                        )

                                    [1] => Array
                                        (
                                            [title] => Account Types
                                            [path] => modules/users-and-accounts/accounts/account-types/
                                            [subItems] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [title] => Add an Account Type
                                                            [path] => modules/users-and-accounts/accounts/account-types/add-an-account-type/
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )
)

1 Ответ

2 голосов
/ 23 октября 2010
<?php

function flattenArray($subitems) {
    $titles = Array() ;
    foreach($subitems as $subkey => $subvalue) {
        if(!is_array($subvalue) 
            || !isset($subvalue['title'])
            || !isset($subvalue['subItems'])
            || !is_array($subvalue['subItems'])) {

            //Leave this element as-is as it doesn't conform to expectations.
            continue ; 
        }
        if(isset($titles[$subvalue['title']])) {
            foreach($subvalue['subItems'] as $subItem) {
                $subitems[$titles[$subvalue['title']]]['subItems'][] = $subItem ;
            }
            unset($subitems[$subkey]) ;
        } else {
            $titles[$subvalue['title']] = $subkey ;
        }
    }
    foreach($subitems as $subkey => $subvalue) {
        if(is_array($subvalue) && isset($subvalue['subItems'])) {
            $subitems[$subkey]['subItems'] = flattenArray($subvalue['subItems']) ;
        }
    }
    return $subitems ;
}
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...