주어진 오프셋을 기반으로 항목을 배열로 이동하고 싶습니다. 현재 프로젝트에서 자주해야하므로 공통 기능을 찾고 있습니다.
$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
}
미리 감사드립니다.
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));
}
명시 적으로 지정된 경우 두 기능 모두 키를 보존합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다