Find all second level keys in multi-dimensional array in php

Viewed 45432

I want to generate a list of the second level of keys used. Each record does not contain all of the same keys. But I need to know what all of the keys are. array_keys() doesn't work, it only returns a list of numbers.

Essentially the output Im looking for is:

action, id, validate, Base, Ebase, Ftype, Qty, Type, Label, Unit

I have a large multi-dimensional array that follows the format:

Array
(
    [0] => Array
        (
            [action] => A
            [id] => 1
            [validate] => yes
            [Base] => Array
                (
                    [id] => 2945
                )

            [EBase] => Array
                (
                    [id] => 398
                )

            [Qty] => 1
            [Type] => Array
                (
                    [id] => 12027
                )

            [Label] => asfhjaflksdkfhalsdfasdfasdf
            [Unit] => asdfas
        )

    [1] => Array
        (
            [action] => A
            [id] => 2
            [validate] => yes
            [Base] => Array
                (
                    [id] => 1986
                )

            [FType] => Array
                (
                    [id] => 6
                )

            [Qty] => 1
            [Type] => Array
                (
                    [id] => 13835
                )

            [Label] => asdssdasasdf
            [Unit] => asdger
        )
)

Thanks for the help!

11 Answers

While @raise answers provides a shortcut, it fails with numeric keys. The following should resolve this:

$secondKeys=array_unique(call_user_func_array('array_merge', array_map('array_keys',$a)));

array_map('array_keys',$a) : Loop through while getting the keys

...'array_merge'... : Merge the keys array

array_unique(... : (optional) Get unique keys.

I hope it helps someone.

UPDATE:

Alternatively you can use

$secondKeys=array_unique(array_merge(...array_map('array_keys', $a)));

That provides same answer as above, and much faster.

My proposal, similar to this answer but faster and using spread operator (PHP 5.6+).

array_merge(...array_values($fields))

if you want move names to array values and reset keys to 0..n just use array_keys in last step.

array_keys(array_merge(...array_values($fields)))

Only if all records have the same keys you could do:

$firstItem = reset($array);
$keys = array_keys($firstItem);

Obviously, this is not the correct answer to this specific question, where the records have different keys. But this might be the question you find when looking how to retrieve second level keys from an array where all keys are the same (I did). If all the record have the same keys, you can simply use the first item in the array with reset() and get the keys from the first item with array_keys().

Related