如何在每次迭代中以自上而下的方式旋转数组元素

时间:2016-10-19 13:23:58

标签: php mysql arrays sorting

我有一个n大小的数组 假设我的原始数组是:

array=(alpha,bravo,charlie,delta,echo,foxtrot);

我想向左旋转上面的数组 ex输出第一次迭代

array=(bravo,charlie,delta,echo,foxtrot,alpha); 

和第二次迭代

array=(charlie,delta,echo,foxtrot,alpha,bravo);

我想在每次迭代中都这样做,直到实现原始数组。

注意:上面的数组我从MySQL输出中获取特定查询。因此原始数组将始终为array=(alpha,bravo,charlie,delta,echo,foxtrot);

提前感谢任何建议和帮助

1 个答案:

答案 0 :(得分:1)

$array = array('alpha','bravo','charlie','delta','echo','foxtrot');

for($i=0; $i< count($array);$i++)
{
    $firstValue = array_shift($array);
    array_push($array, $firstValue);
    var_dump($array); //here you get your array with the first value shifted to the end of the array
}

Result:

array(6) {
  [0]=>
  string(5) "bravo"
  [1]=>
  string(7) "charlie"
  [2]=>
  string(5) "delta"
  [3]=>
  string(4) "echo"
  [4]=>
  string(7) "foxtrot"
  [5]=>
  string(5) "alpha"
}
array(6) {
  [0]=>
  string(7) "charlie"
  [1]=>
  string(5) "delta"
  [2]=>
  string(4) "echo"
  [3]=>
  string(7) "foxtrot"
  [4]=>
  string(5) "alpha"
  [5]=>
  string(5) "bravo"
}
array(6) {
  [0]=>
  string(5) "delta"
  [1]=>
  string(4) "echo"
  [2]=>
  string(7) "foxtrot"
  [3]=>
  string(5) "alpha"
  [4]=>
  string(5) "bravo"
  [5]=>
  string(7) "charlie"
}
array(6) {
  [0]=>
  string(4) "echo"
  [1]=>
  string(7) "foxtrot"
  [2]=>
  string(5) "alpha"
  [3]=>
  string(5) "bravo"
  [4]=>
  string(7) "charlie"
  [5]=>
  string(5) "delta"
}
array(6) {
  [0]=>
  string(7) "foxtrot"
  [1]=>
  string(5) "alpha"
  [2]=>
  string(5) "bravo"
  [3]=>
  string(7) "charlie"
  [4]=>
  string(5) "delta"
  [5]=>
  string(4) "echo"
}
array(6) {
  [0]=>
  string(5) "alpha"
  [1]=>
  string(5) "bravo"
  [2]=>
  string(7) "charlie"
  [3]=>
  string(5) "delta"
  [4]=>
  string(4) "echo"
  [5]=>
  string(7) "foxtrot"
}