您将如何循环旋转数组中的项目向上或向下旋转指定的值。例如
$value = 1; // circularly rotate by 1
$array = array(1,2,3,4,5);
// Should return
array(2,3,4,5,1);
整个阵列逆时针旋转1圈。1
走到尽头,2
成为阵列中的前导号码。我找不到一个可靠的方法来做到这一点。
答案 0 :(得分:0)
您可以将添加值的array_push
函数与数组的末尾和删除并返回数组的第一个元素的array_shift
函数组合。
<?php
$value = 1; // circularly rotate by 1
$array = array(1,2,3,4,5);
while ($value) {
array_push($array, array_shift($array));
$value--;
}
print_r($array);
?>
答案 1 :(得分:0)
使用for
- 循环,指定要移动的项目数,并array_shift()
移动数组。然后将第一个元素添加到移位数组(基本上将第一个项目移动到最后一个元素)
$shift = 2; // How many times you want to move it
$output = array(1, 2, 3, 4, 5);
for ($i = 0; $i < $shift; $i++) {
array_push($output , array_shift($output));
}
print_r($output); // 3, 4, 5, 1, 2