doufen3563 2015-08-03 23:36
浏览 32
已采纳

too long

I want to create my custom array slicing after certain indexes on each function call, I've defined the upperlimit and lower limit of the array indexes such that from starting limit to ending limit, I want to slice my array on each function call. I'm working in PHP and trying to get next array slices on each calling.

Im explaining it more by showing up my function,

function mycustomslicing($startingLimit = 0, $endingLimit = 10){

        if ($startingLimit > 0)
            $startingLimit = $startingLimit*$endingLimit;

 for ($i=0; $i < $endingLimit ; $i++) { 
                $arr2[]  = $arr1[$startingLimit+$i];
            }
}

calling my function:

mycustomslicing(0, 10)
mycustomslicing(11, 20)
mycustomslicing(21,30)

My results:

i'm getting first iteration fine but onwards, it shows me index offsets warning.

My Desired results:

on mycustomslicing(0, 10) call:

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

on mycustomslicing(11, 20) call:

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

on mycustomslicing(21, 30) call:

$arr2 will be, all values from $arr1 from index 21 to 30.
  • 写回答

1条回答 默认 最新

  • douban5644 2015-08-03 23:45
    关注

    Just use the built-in array_slice function. It takes a start and length, so you can subtract your starting limit from ending limit. You also need to pass the array as an argument to the function.

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

    You use this as:

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

    and so on.

    You're getting an error because you're multiplying the start by the end, which is making the starting limit much too high.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作