how to process my array to be associative on first two levels and on third to have simple value

Posted 1 month ago by nikocraft

I'm trying to construct an array where there only strings and the array would look like this key->key->value

To explain it I attached two screenshots below.

I start with this: enter image description here

After my code below I'm 90% there, yet there is an array in value on the third level instead of simple value.

enter image description here

Here is some code:

        $theme = ThemeHandler::with('sections.settings')->find($activeTheme);
        $themeSettings = $theme->sections;
        $themeSettings = collect($themeSettings->toArray());

        // dd($themeSettings);

        $themeSections = [];
        foreach ($themeSettings as $key => $value) {
            $settings = collect($value['settings']);
            $settings = $settings->mapToGroups(function ($item) {
                return [$item['key'] => $item['value']];
            });
            $themeSections[$value['key']] = $settings->toArray(); 
        }
        dd($themeSections);

I would like to end up with this structure

key->key->value

and not

key->key->single_element_array->value

I'm not sure how I end up with an array at the bottom level when I do this

    return [$item['key'] => $item['value']];

inside the mapToGroups, which is a function found here: https://laravel.com/docs/5.8/collections#method-maptogroups

Maybe I misunderstand how mapToGroups work. Anybody has an idea how to get key->key->value structure output?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.