Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create array of mapped array keys

I am trying to create an array which shows the layout of an array.

This would be the input:

    $array = [
        'company' => [
            'contacts' => [
                'first_names',
                'last_name',
                'emails',
                'phones' => [
                    'test'
                ]
            ],
            'addresses' => [
                'postal_code'
            ],
        ]
    ];

And this is what I am trying to get the output to look like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    $array = [
        'company.contacts.phones'
        'company.addresses'
    ];

I have been trying to work this out for hours but haven’t manages to come up with a solution. It needs to work with any layout/depth of input array.

>Solution :

With some Laravel helper and collection this could be done easily
Here it is:

 $array = [
            'company' => [
                'contacts'  => [
                    'first_names',
                    'last_name',
                    'emails',
                    'phones' => [
                        'test',
                    ],
                ],
                'addresses' => [
                    'postal_code',
                ],
            ],
        ];

        collect(Arr::dot($array))->keys()->map(function ($key)
        {
            return Str::beforeLast($key, '.');
        })->unique()->dd();

Output:

array:3 [▼
  0 => "company.contacts"
  3 => "company.contacts.phones"
  4 => "company.addresses"
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading