PHP数组反向递归

我想通过递归反转数组(非关联)。

我的代码:

$array = [1,2,3,4,5,6,7];

function reverseString(&$s) {
    if(count($s) < 2){
        return;
    }
    $len = count($s);
    $temp = $s[0];
    $s[0] = $s[$len - 1];
    $s[$len - 1] = $temp;
    reverseString(array_slice($s, 1, $len - 2));
}

reverseString($array);
print_r($array);

返回:

Array (
    [0] => 7
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 1 )

array_slice是数组部分的链接,对吗? 感谢您的帮助!

评论
  • 自恋狂
    自恋狂 回复

    字符串和数组是两个独立的事物。我稍微整理了一下算法:

    <?php
    $array = [1,2,3,4,5,6,7];
    
    function reverseSequence(&$s) {
        $len = count($s);
        if($len < 2){
            return;
        }
    
        $rest = array_slice($s, 1, $len - 2);
        reverseSequence($rest);
        $s = array_merge([$s[$len - 1]], $rest, [$s[0]]);
    }
    
    reverseSequence($array);
    print_r($array);
    

    obviously输出显然是:

    Array
    (
        [0] => 7
        [1] => 6
        [2] => 5
        [3] => 4
        [4] => 3
        [5] => 2
        [6] => 1
    )