How to get all the key in multi-dimensional array in php

17,564

Solution 1

Try this

function array_keys_multi(array $array)
{
    $keys = array();

    foreach ($array as $key => $value) {
        $keys[] = $key;

        if (is_array($value)) {
            $keys = array_merge($keys, array_keys_multi($value));
        }
    }

    return $keys;
}

Solution 2

If you don't know what the size of the array is going to be, use a recursive function with a foreach loop that calls itself if each $val is an array. If you do know the size, then just foreach through each dimension and record the keys from each.

Something like this:

<?php
function getKeysMultidimensional(array $array) 
{
    $keys = array();
    foreach($array as $key => $value)
    {
        $keys[] = $key;
        if( is_array($value) ) { 
            $keys = array_merge($keys, getKeysMultidimensional($value));
        }
    }

    return $keys;

}
Share:
17,564
aje
Author by

aje

Updated on June 17, 2022

Comments

  • aje
    aje almost 2 years
    Array
    (
        [0] => Array
            (
                [name] => A
                [id] => 1
                [phone] => 416-23-55
                [Base] => Array
                    (
                        [city] => toronto
                    )
    
                [EBase] => Array
                    (
                        [city] => North York                
                    )
    
                [Qty] => 1
            )
    
    (
        [1] => Array
            (
                [name] => A
                [id] => 1
                [phone] => 416-53-66
                [Base] => Array
                    (
                        [city] => qing
                    )
    
                [EBase] => Array
                    (
                        [city] => chong                
                    )
    
                [Qty] => 2
            )
    
    )
    

    How can I get the all the key value with the format "0, name, id, phone, Base, city, Ebase, Qty"?

    Thank you!

  • Mike Q
    Mike Q almost 6 years
    PHP 5.x would not like that array $array in function call.. FYI instead would have $array = array() or just $array)