我想根据给定的偏移量移动数组中的项目。在我目前的项目中,我需要经常这样做,所以我正在寻找一个通用功能。
$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
}
提前谢谢。
当然就像在循环中移动和推动一样简单
function shift($data, $offset) {
do {
$data[] = array_shift($data);
} while (--$offset > 0);
return $data;
}
编辑
如果您还需要处理负偏移,
function shift($data, $offset) {
if ($offset > 0) {
do {
$data[] = array_shift($data);
} while (--$offset > 0);
} elseif ($offset < 0) {
do {
array_unshift($data, array_pop($data));
} while (++$offset < 0);
}
return $data;
}
您可以使用 laravel 集合宏来创建自己的自定义函数。
下面是支持负偏移的宏。
$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)));
});
您也可以在本机PHP中使用集合,但以下函数可以在本机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));
}
如果显式指定,这两个函数都将保留键。