11
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!

Cheesebaron
  • 24,131
  • 15
  • 66
  • 118
aje
  • 325
  • 1
  • 4
  • 14
  • 3
    starting with a foreach() loop would be an idea. –  Jun 27 '12 at 21:13
  • You will either need to do a Breadth First Search or a Depth First Search to find all the keys in the array. In order to do that easily you will need to use a recursive function. – Cheesebaron Jun 27 '12 at 21:15
  • For that exact array `$keys = array_merge(array_keys($array), array_keys(current($array)));` would probably do it. But we could do with knowing exactly what you are trying accomplish by doing this in order to provide advice on the **best** way to do it... – DaveRandom Jun 27 '12 at 21:16

2 Answers2

18

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;
}
Community
  • 1
  • 1
Meliborn
  • 6,495
  • 6
  • 34
  • 53
  • PHP 5.x would not like that array $array in function call.. FYI instead would have $array = array() or just $array) – Mike Q Jun 02 '18 at 20:08
5

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;

}
Lusitanian
  • 11,012
  • 1
  • 41
  • 38