count($ array)返回错误的数组长度

时间:2015-08-17 20:56:11

标签: php arrays permutation

我试图编写一个程序,打印每个可能的数组元素排列。

示例:listPermutations($array),其中$array = array(0,1,2)应返回六个排列0,1,2 0,2,1 1,0,21,2,02,0,12,1,0

我到目前为止的代码是:

<?php

    $myNumber = 3;

    function createArray($objCount){
        for($i = 0; $i < $objCount; $i++){
            $array[$i] = $i;
        }
        return $array;
    }

    function printPermutations($array, $firstObj){
        //echo var_dump($array)."<br>";
        echo count($array)."<br>";
        if(count($array) == 2){
            echo $firstObj.$array[0].$array[1];
            echo $firstObj.$array[1].$array[0];
        }
        else{
            for($i = 0; $i < count($array); $i++){
                $arrayWithoutI = array_splice($array, $i, 1);
                echo var_dump($array)."<br>";
                echo printPermutations($arrayWithoutI, $i).' ';
            }
        }
    }

    function listPermutations($objCount){
        $array = createArray($objCount);
        //echo print_r($array)."<br>";
        printPermutations($array, 0);
    }

    echo listPermutations($myNumber);
?>

代码应以递归方式工作,如下所示:

如果$array的数组长度不等于2,则数组调用$i中的每个元素printPermutaions删除$i并使用{{1}作为 排列的第一个要素。

然而,该计划的输出如下:

$i

为什么删除一个元素后的输出是1而不是2?

1 个答案:

答案 0 :(得分:0)

array splice通过引用获取数组

array array_splice( array &$input , int $offset [, int $length [, mixed $replacement = array() ]] )

表示它正在改变给定的数组。
当你从0迭代到count($array)时,它会计算每次循环运行的数组长度。

$array = [1,2,3,4,5];
count($array); //5
array_splice($array,2);
count($array); //2

array_splice更改数组长度。和count($ array)更改。