gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:19:59 24 4
gpt4 key购买 nike

假设我有这个数组:

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

我有一个开始指示器,$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 内置或自定义函数(类似问题 Treat an array as circular array when selecting elements - PHP )并查看 http://www.w3schools.com/php/php_ref_array.asp但我没有得到想要的结果。任何人都可以给我一个建议吗?

最佳答案

您可以将 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);

输出:

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"
}

关于PHP循环遍历数组从n到n-1个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40842018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com