PHP Need to recursively reverse an array

后端 未结 3 582
遇见更好的自我
遇见更好的自我 2021-01-21 12:57

I need to recursively reverse a HUGE array that has many levels of sub arrays, and I need to preserve all of the keys (which some are int keys, and some are string keys), can so

相关标签:
3条回答
  • 2021-01-21 13:42

    Try this:

    function array_reverse_recursive($arr) {
        foreach ($arr as $key => $val) {
            if (is_array($val))
                $arr[$key] = array_reverse_recursive($val);
        }
        return array_reverse($arr);
    }
    
    0 讨论(0)
  • 2021-01-21 13:49

    Recursively:

    <?php
    
    $a = array(1,3,5,7,9);
    
    print_r($a);
    
    function rev($a) {
      if (count($a) == 1)
        return $a;
    
      return array_merge(rev(array_slice($a, 1, count($a) - 1)), array_slice($a, 0, 1));
    }
    
    $a = rev($a);
    print_r($a);
    
    ?>
    

    output:

    Array
    (
        [0] => 1
        [1] => 3
        [2] => 5
        [3] => 7
        [4] => 9
    )
    Array
    (
        [0] => 9
        [1] => 7
        [2] => 5
        [3] => 3
        [4] => 1
    )
    
    0 讨论(0)
  • 2021-01-21 13:53

    Reversing a HUGE php array in situ (but not recursively):

    function arrayReverse(&$arr){
      if (!is_array($arr) || empty($arr)) {
        return;
      }
      $rev = array();
      while ( false !== ( $val = end($arr) ) ){
        $rev[ key($arr) ] = $val;
        unset( $arr[ key($arr) ] );
      }
      $arr = $rev;
    }
    //usage
    $test = array(5, 'c'=>100, 10, 15, 20);
    arrayReverse($test);
    var_export($test);
    // result: array ( 3 => 20, 2 => 15, 1 => 10, 'c' => 100, 0 => 5, )
    
    0 讨论(0)
提交回复
热议问题