Get keys from multidimensional array recursively

2019-03-05 06:15发布

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 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**.

Tried like this.

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

also this.

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?

2条回答
\"骚年 ilove
2楼-- · 2019-03-05 06:37

This seems to work for me:

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.

查看更多
趁早两清
3楼-- · 2019-03-05 06:45

I used a recursive function:

<?php 

$multiArray = 
array( 4 =>
  array (
    2 =>
    array (
      5 =>
      array (
        1 =>
        array (
          3 =>
          array (
            6 =>
            array (
            )
          )
        )
      )
    )
  )
);


$keysArray = array();
$depth = 0;

function newArray($array, &$keysArray) {

     foreach ($array as $key => $value) {
        $depth++;
        array_push($keysArray, $key);
        if( is_array($value) && $depth < 10 ) { newArray($value, $keysArray ); }

     }

}

newArray($multiArray, $keysArray);
print_r( $keysArray ); // Your expected result
// $keysArray = Array ( [0] => 4 [1] => 2 [2] => 5 [3] => 1 [4] => 3 [5] => 6 )

?>

I used the variable $depth to prevent going loop crazy

查看更多
登录 后发表回答