PHP数组在定义的索引上切片


PHP array slices on defined indexes

我想在每个函数调用的某些索引之后创建我的自定义数组切片,我已经定义了数组索引的上限和下限,以便从开始限制到结束限制,我想在每个函数调用上切片我的数组。我正在PHP中工作,并试图在每次调用上获得下一个数组切片。

我通过展示我的函数来解释它,

function mycustomslicing($startingLimit = 0, $endingLimit = 10){
        if ($startingLimit > 0)
            $startingLimit = $startingLimit*$endingLimit;
 for ($i=0; $i < $endingLimit ; $i++) { 
                $arr2[]  = $arr1[$startingLimit+$i];
            }
}

调用函数:

mycustomslicing(0, 10)
mycustomslicing(11, 20)
mycustomslicing(21,30)
我结果:

我得到第一次迭代很好,但以后,它显示我索引偏移警告。

My Desired results:

mycustomslicing(0, 10)电话:

$arr2 will be, all values from $arr1 from index 0 to 10.

mycustomslicing(11日20)电话:

$arr2 will be, all values from $arr1 from index 11 to 20.

mycustomslicing(21岁,30)电话:

$arr2 will be, all values from $arr1 from index 21 to 30.

使用内置的array_slice函数即可。它有起始值和长度,所以你可以用结束值减去起始值。您还需要将该数组作为参数传递给函数。

function mycustomslicing($arr1, $start, $end) {
    return array_slice($arr1, $start, $end - $start);
}

你可以这样使用:

$arr2 = mycustomslicing($arr1, 0, 10);
$arr2 = mycustomslicing($arr1, 11, 20);

等等

您得到一个错误,因为您将开始与结束相乘,这使得开始限制过高。