PHP循环遍历从n到n-1元素的数组

b19*_*676 2 php arrays loops

假设我有这个数组:

$myArray = array(a, b, c, d, e, f, g);
Run Code Online (Sandbox Code Playgroud)

我有一个开始指示符,$startpos其可能的值可以是从0到myArray的元素数量的任何值.

因此,如果$startpos = 0,所需的打印结果将是a, b, c, d, e, f, g

如果$startpos = 2,所需的打印结果将是c, d, e, f, g, a, b

如果$startpos = 5,所需的打印结果将是f, g, a, b, c, d, e

我一直在通过SO搜索一个php内置或自定义函数(类似问题,在选择元素时将数组视为圆形数组 - PHP)并查看http://www.w3schools.com/php/php_ref_array. asp,但我没有得到理想的结果.有人可以给我一个建议吗?

Kar*_*zin 5

你可以使用array_slice函数array_merge功能如下:

$myArray = array('a', 'b', 'c', 'd', 'e', 'f', 'g');
$startpos = 2;


$output = array_merge(
                 array_slice($myArray,$startpos),
                 array_slice($myArray, 0, $startpos)
                    ); 
var_dump($output);
Run Code Online (Sandbox Code Playgroud)

输出:

array(7) {
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "d"
  [2]=>
  string(1) "e"
  [3]=>
  string(1) "f"
  [4]=>
  string(1) "g"
  [5]=>
  string(1) "a"
  [6]=>
  string(1) "b"
}
Run Code Online (Sandbox Code Playgroud)