PHP:';旋转';阵列?

PHP:';旋转';阵列?,php,arrays,rotation,shift,Php,Arrays,Rotation,Shift,可以在PHP中轻松地“旋转”数组吗 像这样: 1,2,3,4->2,3,4,1 是否有某种内置的PHP函数用于此 $numbers = array(1,2,3,4); array_push($numbers, array_shift($numbers)); print_r($numbers); 输出 Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 1 ) 使用和。逻辑是交换元素。算法可能看

可以在PHP中轻松地“旋转”数组吗

像这样: 1,2,3,4->2,3,4,1

是否有某种内置的PHP函数用于此

  $numbers = array(1,2,3,4);
  array_push($numbers, array_shift($numbers));
  print_r($numbers);
输出

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 1
)

使用和。

逻辑是交换元素。算法可能看起来像-

 for i = 0 to arrayLength - 1
    swap( array[i], array[i+1] )     // Now array[i] has array[i+1] value and 
                                     // array[i+1] has array[i] value.

不可以。请查看文档及其相关功能,以获取一些可用于编写的工具。甚至可能在该页面的注释中实现了一个
array\u rotate
函数


阅读左侧边栏中列出的数组函数也很有价值,可以全面了解PHP中可用的数组函数。

非常简单,可以通过多种方式完成。例如:

$array   = array( 'a', 'b', 'c' );
$array[] = array_shift( $array );

当前的大多数答案都是正确的,但前提是你不在乎你的指数:

$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');
array_push($arr, array_shift($arr));
print_r($arr);
输出:

Array
(
    [baz] => qux
    [wibble] => wobble
    [0] => bar
)
Array
(
    [baz] => qux
    [wibble] => wobble
    [foo] => bar
)
要保留索引,可以执行以下操作:

$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');

$keys = array_keys($arr);
$val = $arr[$keys[0]];
unset($arr[$keys[0]]);
$arr[$keys[0]] = $val;

print_r($arr);
输出:

Array
(
    [baz] => qux
    [wibble] => wobble
    [0] => bar
)
Array
(
    [baz] => qux
    [wibble] => wobble
    [foo] => bar
)

也许有人可以比我的四行方法更简洁地进行旋转,但这仍然有效。

一种维护关键点和旋转的方法。使用与array_push(array,array_shift(array))相同的概念,我们将使用2个array_切片的array_merge

$x=数组(“a”=>1,“b”=>2,“c”=>3,“d”=>4)

将第一个图元移动到末端的步骤

array\u merge(array\u slice($x,1,NULL,true),array\u slice($x,0,1,true)
//“b'=>2,'c'=>3,'d'=>4,'a'=>1

将最后一个图元移到前面

array\u merge(array\u slice($x,count($x)-1,1,true),array\u slice($x,0,
//“d'=>4,'a'=>1,'b'=>2,'c'=>3

$daynamesArray = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
array_push($daynamesArray, array_shift($daynamesArray)); //shift by one
array_push($daynamesArray, array_shift($daynamesArray)); //shift by two
print_r($daynamesArray);
输出从“星期三”开始:


请使用内置函数
array\u reverse
。这是在php中“旋转”数组的最快方法


您可以使用此功能:

    function arr_rotate(&$array,$rotate_count) {
        for ($i = 0; $i < $rotate_count; $i++) {
            array_push($array, array_shift($array));
        }
    }
结果:

 Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 1 [4] => 2 )

Hackerrank上有一个关于数组旋转的任务:

使用
array\u push
array\u shift
提出的解决方案将适用于除最后一个因超时而失败的测试用例之外的所有测试用例。因此,
array\u push
array\u shift
不会为您提供最快的解决方案

以下是更快的方法:

function leftRotation(array $array, $n) {
   for ($i = 0; $i < $n; $i++) {
       $value = array[$i]; unset(array[$i]); array[] = $value;
   }
   return array;
}
函数leftRotation(数组$array,$n){
对于($i=0;$i<$n;$i++){
$value=array[$i];unset(array[$i]);array[]=$value;
}
返回数组;
}

在阵列中循环,以及
移位和
推压可能是旋转阵列的常用方法,但是它经常会弄乱键。更可靠的方法是使用
阵列合并
阵列拼接
的组合

/**
 * Rotates an array.
 * 
 * Numerical indexes will be renumbered automatically.
 * Associations will be kept for keys which are strings.
 * 
 * Rotations will always occur similar to shift and push,
 * where the number of items denoted by the distance are
 * removed from the start of the array and are appended.
 * 
 * Negative distances work in reverse, and are similar to
 * pop and unshift instead.
 * 
 * Distance magnitudes greater than the length of the array
 * can be interpreted as rotating an array more than a full
 * rotation. This will be reduced to calculate the remaining
 * rotation after all full rotations.
 * 
 * @param array $array The original array to rotate.
 * Passing a reference may cause the original array to be truncated.
 * @param int $distance The number of elements to move to the end.
 * Distance is automatically interpreted as an integer.
 * @return array The modified array.
 */
function array_rotate($array, $distance = 1) {
    settype($array, 'array');
    $distance %= count($array);
    return array_merge(
        array_splice($array, $distance), // Last elements  - moved to the start
        $array                          //  First elements - appended to the end
    );
}
// Example rotating an array 180°.
$rotated_180 = array_rotate($array, count($array) / 2);
或者,如果您还发现需要旋转关键点以使其与不同的值匹配,则可以组合
阵列关键点
阵列组合
阵列旋转
,以及
阵列值

/**
 * Rotates the keys of an array while keeping values in the same order.
 * 
 * @see array_rotate(); for function arguments and output.
 */
function array_rotate_key($array, $distance = 1) {
    $keys = array_keys((array)$array);
    return array_combine(
        array_rotate($keys, $distance), // Rotated keys
        array_values((array)$array)    //  Values
    );
}
或者,在保持键顺序相同的情况下旋转值(相当于在匹配的
数组\u rotate\u key
函数调用中调用负距离)

最后,如果您想防止数字索引的重新编号

/**
 * Rotates an array while keeping all key and value association.
 * 
 * @see array_rotate(); for function arguments and output.
 */
function array_rotate_assoc($array, $distance = 1) {
    $keys = array_keys((array)$array);
    $values = array_values((array)$array);
    return array_combine(
        array_rotate($keys, $distance),   // Rotated keys
        array_rotate($values, $distance) //  Rotated values
    );
}
执行一些基准测试可能是有益的,但是,我希望无论使用哪种方法,每个请求的少量旋转都不会显著影响性能


也可以使用自定义排序函数旋转数组,但它很可能过于复杂。例如,
usort

是的,这是我自己做的一个函数,其中$a是数组,$K是要旋转数组的次数:

function solution($A, $K) {

  for($i = 0; $i < $K; $i++): //we cycle $K
    $arrayTemp = $A;
    for($j = 0; $j < count($arrayTemp); $j++): // we cycle the array
       if($j == count($arrayTemp) - 1) $A[0] = $arrayTemp[$j]; // we check for the last position
       else $A[$j + 1] = $arrayTemp[$j]; // all but last position
    endfor;
  endfor;
 return $A;

}
函数解决方案($A,$K){
对于($i=0;$i<$K;$i++)://我们循环$K
$arrayTemp=$A;
对于($j=0;$j
这里有一个函数,可以将数组(零索引数组)旋转到您想要的任何位置:

function rotateArray($inputArray, $rotateIndex) {
  if(isset($inputArray[$rotateIndex])) {
    $startSlice = array_slice($inputArray, 0, $rotateIndex);
    $endSlice = array_slice($inputArray, $rotateIndex);
    return array_merge($endSlice, $startSlice);
  }
  return $inputArray;
}

$testArray = [1,2,3,4,5,6];
$testRotates = [3, 5, 0, 101, -5];

foreach($testRotates as $rotateIndex) {
  print_r(rotateArray($testArray, $rotateIndex));
}

这里有一个提示:您所需要做的就是删除第一个元素(“pop”),并将其添加回最后一个元素(“push”).@Dylan-如果你想自己写一个,可以实现上面的逻辑。如果你只是像向量一样使用数组,索引值并不重要,这很好。但是如果你有一个试图旋转的关联数组,这个方法会破坏你的数组键。请看我的答案,找到一种保存它们的方法。@Cam,你是绝对正确的没错,即使OP也没有提到数组索引,只提到值。您的答案对于那些正在寻找旋转数组元素两部分的解决方案的人来说很有价值。(+1表示您的答案)是的,很明显你的方法对OP来说已经足够了,否则他不会接受的!但是是的,我想我会添加我的答案,以防有人遇到和我一样的问题:)这就是我要找的!向右旋转:
array\u unshift($numbers,array\u pop($numbers))
函数非常简洁,但我觉得可以通过确保循环次数不超过数组元素的次数来稍微改进它。例如
arr\u rotate($xarr,count($xarr));
将以相同的顺序生成结果。添加行
$rotate\u count%=count($array);
将确保最大迭代次数始终小于元素数。golfed:
列表($k,$v)=每个($arr);未设置($arr[$k]);$arr[$k]=$v;
。您可能需要预先设置
重置($arr);
function rotateArray($inputArray, $rotateIndex) {
  if(isset($inputArray[$rotateIndex])) {
    $startSlice = array_slice($inputArray, 0, $rotateIndex);
    $endSlice = array_slice($inputArray, $rotateIndex);
    return array_merge($endSlice, $startSlice);
  }
  return $inputArray;
}

$testArray = [1,2,3,4,5,6];
$testRotates = [3, 5, 0, 101, -5];

foreach($testRotates as $rotateIndex) {
  print_r(rotateArray($testArray, $rotateIndex));
}