简体   繁体   中英

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

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!

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;
}

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM