Home > Mobile >  Create array of mapped array keys
Create array of mapped array keys

Time:05-19

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:

    $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.

CodePudding user response:

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"
]
  • Related