dongliu4320 2013-11-03 21:11
浏览 39
已采纳

PHP数组切片奇怪的行为

I've been recently working with the array_slice function in order to make pagination in my script.

I have an array with 40 values (each value is a thread)

$thread_order_P = $this->forum_handler->orderThreads($forum_threads);

And I want to show only 15 threads a page so I did the following :

$cu_page = $_GET['page'];
$threads_per_page = 15;
$start_f_value = $cu_page-1;
$start_f_value = $start_f_value*$threads_per_page;
$end_f_value = $threads_per_page*$cu_page;
$thread_order = array_slice($thread_order_P, $start_f_value, $end_f_value);

Now, the thing is when I try to display page 1 [echos 15 threads] and 3[echos 10 threads] it works pefectly, but when I try to display page 2 it echos 25 threads instead of 15..

Any ideas?

  • 写回答

1条回答 默认 最新

  • doumie7914 2013-11-03 21:16
    关注

    As Barmar pointed out in the comments, the third argument to array_slice() is the length of the slice, not the end index.

    From the array_slice() documentation:

    If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

    So, change your array_slice() statement to the following:

    $thread_order = array_slice($thread_order_P, $start_f_value, $threads_per_page);
    

    Demo!

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

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能