を使用でき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));
}
明示的に指定されている場合、どちらの関数もキーを保持します。
array_splice() - https://eval.in/885995 – splash58
は、関連するキーですか、それとも値のみですか? –
@ Don'tPanicキーが明示的に指定されていれば、それはうまくいくはずです –