如何在PHP中执行snake循环或如何在每次循环后反转PHP数组我不确定这个方法或技术叫什么,所以我只想把它称为蛇循环。
基本上,我要做的是循环遍历一个数组,然后在下次循环时反转该数组的顺序。
我已经想出了一个似乎有点简单的方法来做到这一点,但我只是不确定这是否是正确的技术,或者是否有更好的方法
<?php
$rounds = 4;
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ;
for($round = 1; $round <= $rounds; $round++){
echo "<h1>Round $round</h1>";
if ($round % 2 == 0) {
krsort($teams);
}else{
asort($teams);
}
foreach($teams as $team){
echo "$team<br />";
}
}
?>
输出:
Round 1
Team 1
Team 2
Team 3
Team 4
Round 2
Team 4
Team 3
Team 2
Team 1
Round 3
Team 1
Team 2
Team 3
Team 4
Round 4
Team 4
Team 3
Team 2
Team 1
基本上,您可以看到,如果$round
是奇数,则该数组对ascending
进行排序,如果是偶数,则对descending
进行排序。
使用php的array_reverse函数。
<?php
$rounds = 4;
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ;
for($round = 1; $round <= $rounds; $round++){
echo "<h1>Round $round</h1>";
echo implode("<br/>", $teams);
$teams = array_reverse($teams);
}
?>
修改代码以实现array_reverse:
<?php
$rounds = 4;
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ;
for($round = 1; $round <= $rounds; $round++){
echo "<h1>Round $round</h1>";
if ($round % 2 == 0) {
$teams = array_reverse($teams);
}
foreach($teams as $team){
echo "$team<br />";
}
}
?>
我认为反转数组是昂贵的,我认为最好是计算反转索引:
array A (6 length) 0,1,2,3,4,5
array B (5 length) 0,1,2,3,4
(len-1)-i
//^ this should calculate the inverted index, examples:
//in the array A, if you are index 3: (6-1)-3 = 2, so 3 turns to 2
//in the array A, if you are index 1: (6-1)-1 = 4, so 1 turns to 4
//in the array B, if you are index 3: (5-1)-3 = 1, so 3 turns to 1
//in the array B, if you are index 1: (5-1)-1 = 3, so 1 turns to 3
我不写PHP,但它应该是这样的:
teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4');
len = teams.length;
myindex; //initializing the var
for(i=0; i<len; i++){
echo "<h1>Round "+ (i+1) +"</h1>";
myindex = i;
if(i%2 == 0) {
myindex = ((len-1) - i);
}
echo team[myindex];
}
array_reverse是返回数组反转的函数。
如果您试图让php数组对象在每个循环中都有相反的内容,那么每次都需要设置数组变量;否则,您可以简单地在每个周期返回arrayreverse的输出。