沃梦达 / 编程问答 / php问题 / 正文

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

Get keys from multidimensional array recursively(递归地从多维数组中获取键)

本文介绍了递归地从多维数组中获取键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的多维数组.它采用 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.

这篇关于递归地从多维数组中获取键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:递归地从多维数组中获取键

基础教程推荐