user103219 user103219 - 2 months ago 11
PHP Question

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

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!

Answer
<?php

// Gets a list of all the 2nd-level keys in the array
function getL2Keys($array)
{
    $result = array();
    foreach($array as $sub) {
        $result = array_merge($result, $sub);
    }        
    return array_keys($result);
}

?>

edit: removed superfluous array_reverse() function