douquejituan938904 2018-11-05 16:52
浏览 14
已采纳

php - 基于范围键返回数组

I have an array with of enumerating numbers, like:

$pageNumbers = array(1,2,3,4,5,6,7,8,9,10);

Now I have an active page number $currentPage and want to have based on this, before and after 2 elements - a total number of 5.

$currentPage = 2:

Return: array(1,2,3,4,5)

$currentPage = 6

Return: array(4,5,6,7,8)

$currentPage = 10

Return: array(6,7,8,9,10)

Unfortunately, I did not come up with an elegant and simple method to solve this (2x while, 1 big foreach and so on). Maybe you have an idea.

My first idea was:

foreach ($pageNumbers as $page) {
        if($page < $currentPage+3 && $page > $currentPage-3) {
            array_push(...);
        }
    }

This will work for the $currentPage = 6, but if $currentPage = 1, it will only return 1,2,3.

  • 写回答

1条回答 默认 最新

  • dtslobe4694 2018-11-05 17:36
    关注

    Use array_slice and cut out the part of the array you need.

    I use an if to see where to slice the array.

    if($currentPage < 3){
        $arr = array_slice($pageNumbers,0,5);
    }elseif($currentPage > count($pageNumbers)-2){
        $arr = array_slice($pageNumbers,-5,5);
    }else{
        $arr = array_slice($pageNumbers,$currentPage-3,5);
    }
    

    See working example below.
    https://3v4l.org/fpOFQ

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

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?