我想为冠军联赛(明天,3月16日星期五)进行自己的四分之一决赛抽签:我有两个问题:首先模数不起作用:它在每次进入后显示“另一场比赛”数组,而我希望它写成每两个匹配(每两个条目)......
第二个问题:有没有更好的方法来“打印”结果?比如没有索引的print_r,我可以在每次输入后说“添加\n
”?
<body>
<?php
$array = array("real", "barça", "bayern", "apoel", "chelsea", "milan", "benfica", "marseille" );
$new = array();
$incr = count($array);
while($incr>0){
$random = rand(0, count($array));
if (!in_array($array[$random], $new)){
$new[] = $array[$random];
if ( (count($new) % 2) ){
$new[] = " -- another match : ";
}
$incr--;
}
}
print_r($new);
?>
<p>results</p>
</body>
感谢您的帮助
答案 0 :(得分:2)
$array = array("real", "barça", "bayern", "apoel", "chelsea", "milan", "benfica", "marseille" );
shuffle($array);
while($a = array_pop($array)) {
echo $a." vs. ".array_pop($array)." <br />";
}
示例输出:
apoel vs. real
barça vs. milan
marseille vs. bayern
chelsea vs. benfica
答案 1 :(得分:1)
模数运作完美:
1 % 2
,所以1
,所以真实,所以你将-- another match
添加到数组3 % 2
,所以1
,所以真实,所以你添加-- another match
等等。无论你想做什么,都不是你告诉服务器做的事情。
你应该做的是这样的事情:
$array = Array(........);
while($a = array_shift($array)) {
$random = rand(0,count($array)-1); // -1 is important!
echo $a." vs. ".$array[$random]."<br />";
unset($array[$random)];
// no need to realign keys since array_shift already does that
}
答案 2 :(得分:0)
模数的工作方式正如你所说的那样。
(count($ new)%2)){
when count($new) = 1, 1 % 2 = 1, = true
when count($new) = 2, 2 % 2 = 0, = false
when count($new) = 3, 3 % 2 = 1, = true
when count($new) = 4, 4 % 2 = 0, = false
when count($new) = 5, 5 % 2 = 1, = true
when count($new) = 6, 6 % 2 = 0, = false