效果
PHP代码
public function demo($params){function moveNext($arr){$length = count($arr);$lastElement = $arr[$length - 1];for ($i = $length - 1; $i > 0; $i--) {$arr[$i] = $arr[$i - 1];}$arr[0] = $lastElement;return $arr;}function moveAndReplace($array, $fromIndex, $toIndex){$length = count($array);$orginVal = $array[$fromIndex];// 如果起始位置在目标位置之前if ($fromIndex < $toIndex) {$startLen = $length - $toIndex - 1;$arrStart = array_slice($array, $toIndex + 1, $startLen);array_splice($array, $toIndex + 1, $startLen, array_fill(0, $startLen, ''));$endLen = $toIndex - $fromIndex + 1;$arrEnd = array_slice($array, $fromIndex, $endLen);array_splice($array, $fromIndex, $endLen, array_fill(0, $endLen, ''));} else { // 如果起始位置在目标位置之后$startLen = $length - $fromIndex - 1;$arrStart = array_slice($array, $fromIndex + 1, $startLen);array_splice($array, $fromIndex + 1, $startLen, array_fill(0, $startLen, ''));$endLen = $fromIndex - $toIndex + 1;$arrEnd = array_slice($array, $toIndex, $endLen);array_splice($array, $toIndex, $endLen, array_fill(0, $endLen, ''));}$arrOld = array_filter($array, function ($val) {return empty($val) ? false : true;});$newArr = array_merge($arrStart, $arrOld, $arrEnd);$newIndex = array_search($orginVal, $newArr);while ($newIndex != $toIndex) {$newArr = moveNext($newArr);$newIndex = array_search($orginVal, $newArr);}return $newArr;}$array = ['A', 'B', 'C', 'D', 'E'];$fromIndex = $params['start']; // A 的位置$toIndex = $params['end']; // C 的位置dump(json_encode($array));dump("{$array[$fromIndex]} ===> $array[$toIndex]");$result = moveAndReplace($array, $fromIndex, $toIndex);dump($result);die;}