这是我的多维数组:
Array
(
[0] => Array
(
[H2H_Id] => T32
[Team1_Id] => T4
[Team1] => Juan Arraya - Max LePivert
[Team2_Id] => T205
[Team2] => Marco Grangeiro - Jeff Morneau
[Winners_Id] => T4
[MatchUps_Id] => M32
)
[1] => Array
(
[H2H_Id] => T39
[Team1_Id] => T205
[Team1] => Marco Grangeiro - Jeff Morneau
[Team2_Id] => T4
[Team2] => Juan Arraya - Max LePivert
[Winners_Id] => T205
[MatchUps_Id] => M32
)
[2] => Array
(
[H2H_Id] => T9
[Team1_Id] => T3
[Team1] => Marco Grangeiro - George Wilkinson
[Team2_Id] => T4
[Team2] => Juan Arraya - Max LePivert
[Winners_Id] => T4
[MatchUps_Id] => M9
)
)
我希望输出为:
Juan Arraya - Max LePivert 1 vs. 1 Marco Grangeiro - Jeff Morneau
Juan Arraya - Max LePivert 1 vs. 0 Marco Grangeiro - George Wilkinson
因此,基本上,我想通过使用MatchUps_Id
分别显示不同的比赛,并打印球队Team1
和Team2
的名称。基于Winners_Id
,我想添加一个计数器来记录每支球队每场比赛的胜利。
请记住,这些结果来自用户输入,这将使多维数组在每次我请求field1
和field2
传递的用户输入时都有所不同。
这就是我迄今为止的代码:
$query2 = "SELECT HeadToHead.H2HNo H2H_Id, H2HTeam1Id Team1_Id, H2HTeam1 Team1, H2HTeam2Id Team2_Id, H2HTeam2 Team2, WinnersId Winners_Id, MatchUps.MatchUpsNo MatchUps_Id
FROM HeadToHead
JOIN MatchUps ON HeadToHead.MatchUpsNo=MatchUps.MatchUpsNo
WHERE ((H2HTeam1 LIKE '%$field1%' OR H2HTeam2 LIKE '%$field1%') AND (H2HTeam1 LIKE '%$field2%' OR H2HTeam2 LIKE '%$field2%'))";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows($result2);
$arr2 = array();
if($num2 > 0) {
while($row2 = mysql_fetch_assoc($result2)) {
$arr2[] = $row2;
}
}
我从上面的代码中得到了想要的结果。
我想我已经在这件事上做了很多研究,但我试图完成的似乎与现在不同。
非常感谢您的帮助。
您可以通过'MatchUps_Id'
将匹配分组在一起,如下所示:
foreach ($arr2 as $match) {
// create some short ids to make the next part more readable
$id = $match['MatchUps_Id'];
$t1 = $match['Team1_Id'];
$t2= $match['Team2_Id'];
if (!isset($matchups[$id][$t1]['name'])) {
// initialize if this matchup has not yet been created
$matchups[$id][$t1]['name'] = $match['Team1'];
$matchups[$id][$t2]['name'] = $match['Team2'];
$matchups[$id][$t1]['wins'] = (int) ($match['Winners_Id'] == $match['Team1_Id']);
$matchups[$id][$t2]['wins'] = (int) ($match['Winners_Id'] == $match['Team2_Id']);
} else {
// increment wins if the matchup already exists
$matchups[$id][$t1]['wins'] += $match['Winners_Id'] == $match['Team1_Id'];
$matchups[$id][$t2]['wins'] += $match['Winners_Id'] == $match['Team2_Id'];
}
}
使用$t1
和$t2
作为二级密钥,可以增加各个团队的获胜次数,而无需知道哪个是哪个。表达式$match['Winners_Id'] == $match['Team1_Id']
返回一个布尔值,当与+=
一起使用时,该布尔值将隐式转换为整数0
或1
,但在初始化时必须使用(int)
显式转换。
在你对你的阵列进行分组并计算获胜次数后,你可以输出这样的结果:
foreach ($matchups as $matchup) {
list($a, $b) = array_values($matchup);
echo "$a[name] $a[wins] vs. $b[wins] $b[name]<br>";
}