php中数组的右旋转

som*_*ove 5 php arrays

例如我有一个数组

$a = [1,2,3,4,5]; 
Run Code Online (Sandbox Code Playgroud)

由此$a,如何获取最后一个数组并将其设置为第一个[5,1,2,3,4] ,以及如何获取最后两个数组以使其像[4,5,1,2,3]

Qir*_*rel 6

您可以组合使用array_pop(),这会弹出数组的最后一个元素,并将array_unshift()其推到数组的前面。您可以为此创建一个简单的函数,

function array_pop_unshift($array) {
    array_unshift($array, array_pop($array));
    return $array;
}
Run Code Online (Sandbox Code Playgroud)

然后将其用作

$a = [1,2,3,4,5];
$new = array_pop_unshift($a);
print_r($new); // [5,1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

要继续移动它,只需再次调用该函数直到完成,例如通过循环for

$a = [1,2,3,4,5];
for ($i = 0; $i < 2; $i++) {
    $new = array_pop_unshift($a);
}
print_r($new); // [4,5,1,2,3]
Run Code Online (Sandbox Code Playgroud)


Aas*_*aba 1

to take last one and set it first 这称为右旋转。

$k移位的单位数。$a是数组。

for($x=0; $x < $k; $x++){

    //remove last element
    $last = array_pop($a);

    //push last element to the beginning
    array_unshift($a, $last);

}
Run Code Online (Sandbox Code Playgroud)

array_pop()弹出并返回数组最后一个元素的值,将数组缩短一个元素。 https://www.php.net/manual/en/function.array-pop.php

array_unshift() 将传递的元素添加到数组的前面 https://www.php.net/manual/en/function.array-unshift.php

您可以创建一个函数,该函数接受两个参数$k(旋转次数)和$a(数组),并在执行正确的旋转次数后返回数组$k

function rotateRight($a, $k){
    for($x=0; $x < $k; $x++){
       //remove last element
       $last = array_pop($a);
       //push last element to the beginning
       array_unshift($a, $last);
    }
    return $a;
}
Run Code Online (Sandbox Code Playgroud)

然后相应地调用它。

例子:

$a = [1,2,3,4,5]; 

$a_one_shift = rotateRight($a, 1);
//  [5,1,2,3,4]; 

$a_two_shift = rotateRight($a_one_shift, 1);
// [4,5,1,2,3];

Run Code Online (Sandbox Code Playgroud)

或者你可以传递 2 直接得到右旋两次后的数组。

$a_new = rotateRight($a, 2);
// [4,5,1,2,3];
Run Code Online (Sandbox Code Playgroud)