在php中查找多维数组中的所有二级键

时间:2022-06-12 21:31:38

I want to generate a list of the second level of keys used. Each record does not contain all of the same keys. But I need to know what all of the keys are. array_keys() doesn't work, it only returns a list of numbers.

我想生成一个使用的第二级密钥列表。每条记录都不包含所有相同的密钥。但我需要知道所有的密钥是什么。 array_keys()不起作用,它只返回一个数字列表。

Essentially the output Im looking for is:

基本上我想要的输出是:

action, id, validate, Base, Ebase, Ftype, Qty, Type, Label, Unit

动作,id,验证,Base,Ebase,Ftype,数量,类型,标签,单位

I have a large multi-dimensional array that follows the format:

我有一个遵循以下格式的大型多维数组:

Array
(
    [0] => Array
        (
            [action] => A
            [id] => 1
            [validate] => yes
            [Base] => Array
                (
                    [id] => 2945
                )

            [EBase] => Array
                (
                    [id] => 398
                )

            [Qty] => 1
            [Type] => Array
                (
                    [id] => 12027
                )

            [Label] => asfhjaflksdkfhalsdfasdfasdf
            [Unit] => asdfas
        )

    [1] => Array
        (
            [action] => A
            [id] => 2
            [validate] => yes
            [Base] => Array
                (
                    [id] => 1986
                )

            [FType] => Array
                (
                    [id] => 6
                )

            [Qty] => 1
            [Type] => Array
                (
                    [id] => 13835
                )

            [Label] => asdssdasasdf
            [Unit] => asdger
        )
)

Thanks for the help!

谢谢您的帮助!

9 个解决方案

#1


17  

<?php

// Gets a list of all the 2nd-level keys in the array
function getL2Keys($array)
{
    $result = array();
    foreach($array as $sub) {
        $result = array_merge($result, $sub);
    }        
    return array_keys($result);
}

?>

edit: removed superfluous array_reverse() function

编辑:删除多余的array_reverse()函数

#2


8  

array_keys(call_user_func_array('array_merge', $a));

Merge all values and retrieve the resulting keys.

合并所有值并检索生成的键。

#3


6  

foreach($bigArray as $array){    
    foreach($array as $key=>$value){
        echo $key;
    }
}

That should do what you want.

那应该做你想要的。

#4


5  

What about something like this :

这样的事情怎么样:

$your_keys = array_keys($your_array[0]);

Of course, this is considering all sub-arrays have the same keys ; in this case, you only need the keys of the first sub-array (no need to iterate over all first-level sub-arrays, I guess)

当然,这是考虑所有子阵列具有相同的键;在这种情况下,你只需要第一个子数组的键(我猜不需要迭代所有的第一级子数组)


And, as a shortened / simplified example :

而且,作为一个缩短/简化的例子:

$your_array = array(
    array(
        'action' => 'A',
        'id' => 1,
        'base' => array('id' => 145),
    ),
    array(
        'action' => 'B',
        'id' => 2,
        'base' => array('id' => 145),
    ),
    array(
        'action' => 'C',
        'id' => 3,
        'base' => array('id' => 145),
    )
);

$your_keys = array_keys($your_array[0]);
var_dump($your_keys);

Will get you :

会得到你:

array
  0 => string 'action' (length=6)
  1 => string 'id' (length=2)
  2 => string 'base' (length=4)

You can the use implode to get the string you asked for :

您可以使用implode来获取您要求的字符串:

echo implode(', ', $your_keys);

will get you :

会得到你:

action, id, base

ie, the list of the keys of the first sub-array.

即,第一子阵列的键列表。

#5


3  

One liner:

一个班轮:

$keys=array_unique(array_reduce(array_map('array_keys',$data),'array_merge',[]));

Or in a function:

或者在一个功能中:

function get_array_children_keys($data) {
    return array_unique(
        array_reduce(array_map('array_keys', $data), 'array_merge', [])
    );
}

Now lets break this down with an example, here is some sample data:

现在让我们通过一个例子来解决这个问题,这里有一些示例数据:

[
    ['key1' => 0],
    ['key1' => 0, 'key2' => 0],
    ['key3' => 0]
]

Starting with the inner most function, we run array_map with the array_keys function:

从最内层函数开始,我们使用array_keys函数运行array_map:

array_map('array_keys', $data)

This gives us the keys of from all child arrays

这为我们提供了所有子数组的关键

[
    ['key1'],
    ['key1', 'key2'],
    ['key3']
]

Then we run the array_reduce on the data with the array_merge callback and an empty array as the initial value:

然后我们使用array_merge回调和一个空数组作为初始值对数据运行array_reduce:

array_reduce(..., 'array_merge', []);

This converts our multiple arrays into 1 flat array:

这将我们的多个数组转换为1个平面数组:

[
    'key1',
    'key1',
    'key2',
    'key3'
]

Now we strip out our duplicates with array_unique:

现在我们用array_unique删除我们的重复项:

array_unique(...)

And end up with all our keys:

最后得到我们所有的钥匙:

[
    'key1',
    'key2',
    'key3'
]

#6


1  

function  __getAll2Keys($array_val){
        $result = array();
        $firstKeys = array_keys($array_val);
        for($i=0;$i<count($firstKeys);$i++){
            $key = $firstKeys[$i];
            $result = array_merge($result,array_keys($array_val[$key]));
        }
        return $result;
    }

try this function. It will return as you want.

试试这个功能。它将根据您的需要返回。

#7


0  

Maybe you can use array_map function, which allows you to avoid array iteration and return an array with the keys you need as values.

也许你可以使用array_map函数,它允许你避免数组迭代并返回一个数组,其中包含你需要的键作为值。

will be like this

会是这样的

$newArray = array_map(function($value){return array_keys($value);},$yourArray);

var_dump($newArray);

array (size=2)
  0 => 
    array (size=9)
      0 => string 'action' (length=6)
      1 => string 'id' (length=2)
      2 => string 'validate' (length=8)
      3 => string 'Base' (length=4)
      4 => string 'EBase' (length=5)
      5 => string 'Qty' (length=3)
      6 => string 'Type' (length=4)
      7 => string 'Label' (length=5)
      8 => string 'Unit' (length=4)
  1 => 
    array (size=9)
      0 => string 'action' (length=6)
      1 => string 'id' (length=2)
      2 => string 'validate' (length=8)
      3 => string 'Base' (length=4)
      4 => string 'FType' (length=5)
      5 => string 'Qty' (length=3)
      6 => string 'Type' (length=4)
      7 => string 'Label' (length=5)
      8 => string 'Unit' (length=4)

#8


0  

With this function you can get all keys from a multidimensional array

使用此功能,您可以从多维数组中获取所有键

function arrayKeys($array, &$keys = array()) {        
        foreach ($array as $key => $value) {
            $keys[] = $key;
            if (is_array($value)) {                
                $this->arrayKeys($value, $keys);
            }
        }
        return $keys;
}

#9


0  

While @raise answers provides a shortcut, it fails with numeric keys. The following should resolve this:

虽然@raise答案提供了一个快捷方式,但它使用数字键失败。以下应解决此问题:

$secondKeys=array_unique(call_user_func_array('array_merge', array_map('array_keys',$a)));

array_map('array_keys',$a) : Loop through while getting the keys

array_map('array_keys',$ a):获取密钥时循环访问

...'array_merge'... : Merge the keys array

...'array_merge'...:合并keys数组

array_unique(... : (optional) Get unique keys.

array_unique(... :(可选)获取唯一键。

I hope it helps someone.

我希望它对某人有帮助。

UPDATE:

更新:

Alternatively you can use

或者你可以使用

$secondKeys=array_unique(array_merge(...array_map('array_keys', $a)));

That provides same answer as above, and much faster.

这提供了与上面相同的答案,并且更快。

#1


17  

<?php

// Gets a list of all the 2nd-level keys in the array
function getL2Keys($array)
{
    $result = array();
    foreach($array as $sub) {
        $result = array_merge($result, $sub);
    }        
    return array_keys($result);
}

?>

edit: removed superfluous array_reverse() function

编辑:删除多余的array_reverse()函数

#2


8  

array_keys(call_user_func_array('array_merge', $a));

Merge all values and retrieve the resulting keys.

合并所有值并检索生成的键。

#3


6  

foreach($bigArray as $array){    
    foreach($array as $key=>$value){
        echo $key;
    }
}

That should do what you want.

那应该做你想要的。

#4


5  

What about something like this :

这样的事情怎么样:

$your_keys = array_keys($your_array[0]);

Of course, this is considering all sub-arrays have the same keys ; in this case, you only need the keys of the first sub-array (no need to iterate over all first-level sub-arrays, I guess)

当然,这是考虑所有子阵列具有相同的键;在这种情况下,你只需要第一个子数组的键(我猜不需要迭代所有的第一级子数组)


And, as a shortened / simplified example :

而且,作为一个缩短/简化的例子:

$your_array = array(
    array(
        'action' => 'A',
        'id' => 1,
        'base' => array('id' => 145),
    ),
    array(
        'action' => 'B',
        'id' => 2,
        'base' => array('id' => 145),
    ),
    array(
        'action' => 'C',
        'id' => 3,
        'base' => array('id' => 145),
    )
);

$your_keys = array_keys($your_array[0]);
var_dump($your_keys);

Will get you :

会得到你:

array
  0 => string 'action' (length=6)
  1 => string 'id' (length=2)
  2 => string 'base' (length=4)

You can the use implode to get the string you asked for :

您可以使用implode来获取您要求的字符串:

echo implode(', ', $your_keys);

will get you :

会得到你:

action, id, base

ie, the list of the keys of the first sub-array.

即,第一子阵列的键列表。

#5


3  

One liner:

一个班轮:

$keys=array_unique(array_reduce(array_map('array_keys',$data),'array_merge',[]));

Or in a function:

或者在一个功能中:

function get_array_children_keys($data) {
    return array_unique(
        array_reduce(array_map('array_keys', $data), 'array_merge', [])
    );
}

Now lets break this down with an example, here is some sample data:

现在让我们通过一个例子来解决这个问题,这里有一些示例数据:

[
    ['key1' => 0],
    ['key1' => 0, 'key2' => 0],
    ['key3' => 0]
]

Starting with the inner most function, we run array_map with the array_keys function:

从最内层函数开始,我们使用array_keys函数运行array_map:

array_map('array_keys', $data)

This gives us the keys of from all child arrays

这为我们提供了所有子数组的关键

[
    ['key1'],
    ['key1', 'key2'],
    ['key3']
]

Then we run the array_reduce on the data with the array_merge callback and an empty array as the initial value:

然后我们使用array_merge回调和一个空数组作为初始值对数据运行array_reduce:

array_reduce(..., 'array_merge', []);

This converts our multiple arrays into 1 flat array:

这将我们的多个数组转换为1个平面数组:

[
    'key1',
    'key1',
    'key2',
    'key3'
]

Now we strip out our duplicates with array_unique:

现在我们用array_unique删除我们的重复项:

array_unique(...)

And end up with all our keys:

最后得到我们所有的钥匙:

[
    'key1',
    'key2',
    'key3'
]

#6


1  

function  __getAll2Keys($array_val){
        $result = array();
        $firstKeys = array_keys($array_val);
        for($i=0;$i<count($firstKeys);$i++){
            $key = $firstKeys[$i];
            $result = array_merge($result,array_keys($array_val[$key]));
        }
        return $result;
    }

try this function. It will return as you want.

试试这个功能。它将根据您的需要返回。

#7


0  

Maybe you can use array_map function, which allows you to avoid array iteration and return an array with the keys you need as values.

也许你可以使用array_map函数,它允许你避免数组迭代并返回一个数组,其中包含你需要的键作为值。

will be like this

会是这样的

$newArray = array_map(function($value){return array_keys($value);},$yourArray);

var_dump($newArray);

array (size=2)
  0 => 
    array (size=9)
      0 => string 'action' (length=6)
      1 => string 'id' (length=2)
      2 => string 'validate' (length=8)
      3 => string 'Base' (length=4)
      4 => string 'EBase' (length=5)
      5 => string 'Qty' (length=3)
      6 => string 'Type' (length=4)
      7 => string 'Label' (length=5)
      8 => string 'Unit' (length=4)
  1 => 
    array (size=9)
      0 => string 'action' (length=6)
      1 => string 'id' (length=2)
      2 => string 'validate' (length=8)
      3 => string 'Base' (length=4)
      4 => string 'FType' (length=5)
      5 => string 'Qty' (length=3)
      6 => string 'Type' (length=4)
      7 => string 'Label' (length=5)
      8 => string 'Unit' (length=4)

#8


0  

With this function you can get all keys from a multidimensional array

使用此功能,您可以从多维数组中获取所有键

function arrayKeys($array, &$keys = array()) {        
        foreach ($array as $key => $value) {
            $keys[] = $key;
            if (is_array($value)) {                
                $this->arrayKeys($value, $keys);
            }
        }
        return $keys;
}

#9


0  

While @raise answers provides a shortcut, it fails with numeric keys. The following should resolve this:

虽然@raise答案提供了一个快捷方式,但它使用数字键失败。以下应解决此问题:

$secondKeys=array_unique(call_user_func_array('array_merge', array_map('array_keys',$a)));

array_map('array_keys',$a) : Loop through while getting the keys

array_map('array_keys',$ a):获取密钥时循环访问

...'array_merge'... : Merge the keys array

...'array_merge'...:合并keys数组

array_unique(... : (optional) Get unique keys.

array_unique(... :(可选)获取唯一键。

I hope it helps someone.

我希望它对某人有帮助。

UPDATE:

更新:

Alternatively you can use

或者你可以使用

$secondKeys=array_unique(array_merge(...array_map('array_keys', $a)));

That provides same answer as above, and much faster.

这提供了与上面相同的答案,并且更快。