Get keys from multidimensional array recursively

后端 未结 2 1576
广开言路
广开言路 2021-01-28 20:36

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

array(1) {
  [4]=>
  array(1) {
    [2]=>
    array(1) {
      [5]=>
      arra         


        
相关标签:
2条回答
  • 2021-01-28 21:13

    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

    0 讨论(0)
  • 2021-01-28 21: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.

    0 讨论(0)
提交回复
热议问题