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

44,350

Solution 1

<?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

Solution 2

array_keys(call_user_func_array('array_merge', $a));

Merge all values and retrieve the resulting keys.

Solution 3

One liner:

$keys=array_unique(array_reduce(array_map('array_keys',$data),'array_merge',[]));

Or in a function:

function get_array_children_keys($data) {
    return array_unique(
        array_reduce(array_map('array_keys', $data), 'array_merge', [])
    );
}

Now lets break this down with an example, here is some sample data:

[
    ['key1' => 0],
    ['key1' => 0, 'key2' => 0],
    ['key3' => 0]
]

Starting with the inner most function, we run array_map with the array_keys function:

array_map('array_keys', $data)

This gives us the keys of from all child arrays

[
    ['key1'],
    ['key1', 'key2'],
    ['key3']
]

Then we run the array_reduce on the data with the array_merge callback and an empty array as the initial value:

array_reduce(..., 'array_merge', []);

This converts our multiple arrays into 1 flat array:

[
    'key1',
    'key1',
    'key2',
    'key3'
]

Now we strip out our duplicates with array_unique:

array_unique(...)

And end up with all our keys:

[
    'key1',
    'key2',
    'key3'
]

Solution 4

foreach($bigArray as $array){    
    foreach($array as $key=>$value){
        echo $key;
    }
}

That should do what you want.

Solution 5

What about something like this :

$your_keys = array_keys($your_array[0]);

Of course, this is considering all sub-arrays have the same keys ; in this case, you only need the keys of the first sub-array (no need to iterate over all first-level sub-arrays, I guess)


And, as a shortened / simplified example :

$your_array = array(
    array(
        'action' => 'A',
        'id' => 1,
        'base' => array('id' => 145),
    ),
    array(
        'action' => 'B',
        'id' => 2,
        'base' => array('id' => 145),
    ),
    array(
        'action' => 'C',
        'id' => 3,
        'base' => array('id' => 145),
    )
);

$your_keys = array_keys($your_array[0]);
var_dump($your_keys);

Will get you :

array
  0 => string 'action' (length=6)
  1 => string 'id' (length=2)
  2 => string 'base' (length=4)

You can the use implode to get the string you asked for :

echo implode(', ', $your_keys);

will get you :

action, id, base

ie, the list of the keys of the first sub-array.

Share:
44,350

Related videos on Youtube

user103219
Author by

user103219

Updated on October 05, 2020

Comments

  • user103219
    user103219 over 3 years

    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!

  • user103219
    user103219 over 14 years
    Thanks Pascal unfortunately each array does not contain the same keys.
  • user103219
    user103219 over 14 years
    thanks inkedmn - I had first attempted your first version (prior to your edit) and it obviously didn't work. This one worked just fine, then a simple if statement to check for duplicates and I had my data.
  • Pascal MARTIN
    Pascal MARTIN over 14 years
    Ho, too bad :-( In this case, what about using array_keys on each sub-array, and, then, array_merge on the lists of keys of those sub-arrays ?
  • user103219
    user103219 over 14 years
    Works great, no need to check values for repeated keys!
  • Øystein Riiser Gundersen
    Øystein Riiser Gundersen over 14 years
    Why the call to array_reverse()?
  • user3529201
    user3529201 over 14 years
    @gunderwonder - it turns the keys into values - so that array_merge() will merge all the keys together
  • Øystein Riiser Gundersen
    Øystein Riiser Gundersen over 14 years
    array_merge() merges any non-numeric keys shared between the arrays and array_reverse() just reverses the order of the keys. Your function works just as well without array_reverse()
  • Sarah
    Sarah over 13 years
    Worked like a charm.Nice ,clean and pretty simple too.
  • Hontoni
    Hontoni about 10 years
    that just switches the keys to be values
  • y2k-shubham
    y2k-shubham over 3 years
    very good soln except that array_merge doesn't preserve keys
  • y2k-shubham
    y2k-shubham over 3 years
    For key-preserving one-liner, @Sy Holloway's soln works
  • Mike R
    Mike R about 3 years
    This one was perfect for my needs as well. I was trying to get nested key values that looked ``` [applications] => Array ( [0] => Array ( [id] => 2 [name] => WordPress [short_name] => wordpress [deploy_name] => WordPress on Ubuntu 18.04 x64 ``` This worked to get me the id and name as key => values ``` foreach ($apps as $app) { foreach ($app as $key=>$value) { $vultr_apps_nice[$value['id']] = $value['name']; } } ```
  • mickmackusa
    mickmackusa almost 3 years
    The first level is indexed in the OP's question, so array_values() is not necessary for this specific question.