阵列循环从中间开始

时间:2018-12-28 03:08:41

标签: php arrays loops

我有以下数组:

$alphabet = array("a","b","c","d","e","f","g")

如果我想从“ d” 开始并遍历数组以输出为d,e,f,g,a,b,c

如何实现?

2 个答案:

答案 0 :(得分:2)

<?php
$alphabet = array("a","b","c","d","e","f","g");
$startIndex = 3;// index of d
$count = count($alphabet);
for($x = 0; $x < count($alphabet); $x++){
    $index = $x + $startIndex < $count  ? $x + $startIndex :  $x + $startIndex -  $count;
    echo $alphabet[$index];
}

输出

  

defgabc

请参阅live demo

如果您不知道所需元素的索引,则可以使用array_search

$startIndex = array_search('d', $alphabet);

答案 1 :(得分:1)

您可以尝试使用array_slice函数来实现所需的功能:

<?php
$alphabet = array("a","b","c","d","e","f","g");

// find the index of the start element in the original array
$index = array_search("d", $alphabet);

// iterate the array from starting point to the end
foreach (array_slice($alphabet, $index) as $value) {
    echo $value, ",";
}

// iterate the array from the very beginning to the starting point
foreach (array_slice($alphabet, 0, $index) as $value) {
    echo $value, ",";
}