dongtuoji5396 2017-10-24 15:23
浏览 94
已采纳

有人能提供一般功能,根据给定的偏移量从数组中移动项目吗?

I would like to shift the items in array based on given offset. In my current project I need to do this often so I am looking for a common function.

$data = [1, 2, 3, 4, 5, 6];

$data = shift($data, 2);

dd($data); //should result into [3, 4, 5, 6, 1, 2]

function shift($data, $offset) {
// general code
}

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • drza10046 2017-10-24 15:32
    关注

    You can use laravel collection macro to create your own custom functions.

    Below is the macro which will support the negative offset as well.

    $collection = collect([1, 2, 3, 4, 5, 6]);
    
    $rotate = $collection->rotate(2);
    
    $rotate->toArray();
    
    // [3, 4, 5, 6, 1, 2]
    
    Collection::macro('rotate', function ($offset) {
        if ($this->isEmpty()) {
            return new static;
        }
        $count = $this->count();
        $offset %= $count;
        if ($offset < 0) {
            $offset += $count;
        }
        return new static($this->slice($offset)->merge($this->take($offset)));
    });
    

    You can use collection in native PHP as well but below function can be used in native PHP.

    function array_rotate($array, $shift) {
        $shift %= count($array); 
        if($shift < 0) $shift += count($array);
        return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true));
    }
    

    Both functions will preserve keys if explicitly specified.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口