如何获得在PHP多维数组的所有关键(How to get all the key in multi-

2019-06-25 20:38发布

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
        )

)

我怎样才能获得所有的格式以“0,姓名,身份证,手机,基地城市,EBASE,数量”的键值?

谢谢!

Answer 1:

试试这个

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


Answer 2:

如果你不知道什么是数组的大小将是,使用递归函数foreach循环调用本身如果每个$ VAL是一个数组。 如果你知道的大小,则刚刚经历的每个维度的foreach并记录每个按键。

事情是这样的:

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

}


文章来源: How to get all the key in multi-dimensional array in php