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条)

报告相同问题?

悬赏问题

  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题