如何在php中获取多维数组中的所有键?

时间:2022-04-03 13:36:43
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"?

如何使用“0,name, id, phone, Base, city, Ebase, Qty”格式获取所有键值?

Thank you!

谢谢你!

2 个解决方案

#1


12  

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

#2


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.

如果不知道数组的大小,可以使用一个带有foreach循环的递归函数,如果每个$val都是一个数组,那么这个循环就会调用自己。如果您确实知道大小,那么只需对每个维度进行foreach并记录每个维度的键。

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;

}

#1


12  

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

#2


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.

如果不知道数组的大小,可以使用一个带有foreach循环的递归函数,如果每个$val都是一个数组,那么这个循环就会调用自己。如果您确实知道大小,那么只需对每个维度进行foreach并记录每个维度的键。

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;

}