递归地从多维数组中获取键

2022-01-04 00:00:00 arrays multidimensional-array key get php

我有这样的多维数组.它采用 var_dump() 格式.

I have multidimensional array like this. It is in var_dump() formatting.

array(1) {
  [4]=>
  array(1) {
    [2]=>
    array(1) {
      [5]=>
      array(1) {
        [1]=>
        array(1) {
          [3]=>
          array(1) {
            [6]=>
            array(0) {
            }
          }
        }
      }
    }
  }
}

aka $multiArray,我想从中获取所有键并将它们设置为像这样获取数组.

aka $multiArray and i want to get all keys from it and set them to get array like this.

[0=>4, 1=>2, 2=>5, 3=>1, 4=>3, 5=>6] aka **$keysArray**.

这样试过.

foreach( new RecursiveIteratorIterator(
    new RecursiveArrayIterator(**$multiArray**),
    RecursiveIteratorIterator::SELF_FIRST)
    as $key => $value) {
        **$keysArray[]** = $key;
    }

还有这个.

function array_keys_multi(array $array) {
        $keys = [];

        foreach ($array as $key => $value) {
            $keys[] = $key;
            if (is_array($value)) {
                $keys = array_merge($keys, $this->array_keys_multi($value));
            }
        }

        return $keys;
    }

但它们都返回了错误的数据.我怎样才能得到所有的钥匙?

but both of them returns incorrect data. How can i get all keys?

推荐答案

这似乎对我有用:

function array_keys_recursive(array $arr) {
    foreach($arr as $key => $value) {
        $return[] = $key;
        if(is_array($value)) $return = array_merge($return, array_keys_recursive($value));
    }
    return $return;
}

顺便说一下,与您的基本相同,也可以使用.

Basically identical to yours, which also works, by the way.

相关文章