【发布时间】:2021-03-31 19:50:38
【问题描述】:
我正在使用来自 Leaguepedia 的 api 来接收信息。
所以我有这个代码来显示一个冠军在锦标赛中被选中了多少次,它工作正常,但是 现在我试图显示胜率,但我遇到了问题,
例如:
辛德拉选了 4 次 - 赢了 3 次 - 胜率 = 75%,这是我期望的结果;
Gragas 选择了 3 次 - 赢了 3 次 - 胜率 = 100%,这是我期望的结果;
我收到的是:
辛德拉选择了 4 次 - 赢了 1 次 - 胜率 = 25%
Gragas 选择了 3 次 - 赢得 1 次 - 胜率 = 33,33% ,每个冠军的胜利显示为 1(图片)
我知道我的问题可能出在“开关/外壳”上,但我不知道如何解决
那么我怎样才能修复我的代码以显示正确的赢率。
谢谢
这是我的代码
<?php
// $Result is a CURL coming from leaguepedia api
$result = json_decode($file_contents);
$heroPicks = [];
$heroVictory = [];
// Double foreach to access the values from leaguepedia api
foreach ($result as $d) {
foreach ($d as $data) {
//$data->title->Team1Picks and
// $data->title->Team2Picks is coming from leaguepedia api
//as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
// So i need to explode and merge to an array to count.
$picks1 = explode(",", $data->title->Team1Picks);
$picks2 = explode(",", $data->title->Team2Picks);
$picks = array_merge($picks1, $picks2);
// this switch is to check if
// $data->title->Winner == 1 , it means that
// $picks1 won the game else == 2 $picks2
// won the game ($data->title->Winner is coming from api aswell)
switch ($data->title->Winner) {
case 1:
$w = $picks1;
break;
case 2:
$w = $picks2;
break;
}
//foreach to count the times a champion was picked
foreach ($picks as $pick) {
$pick = trim($pick);
if (!array_key_exists($pick, $heroPicks)) {
$heroPicks[$pick] = 0;
}
$heroPicks[$pick] += 1;
}
//foreach to count how many times a champion won a game
foreach ($w as $victory) {
$victory = trim($victory);
if (!array_key_exists($victory, $heroVictory)) {
$heroVictory[$victory] = 0;
}
$heroVictory[$victory] += 1;
}
}
}
//sorting the arrays
uasort(
$heroPicks,
function ($a, $b) {
return $a - $b;
}
);
uasort(
$heroVictory,
function ($c, $d) {
return $c - $d;
}
);
$heroPicks = array_reverse($heroPicks);
$heroVictory = array_reverse($heroVictory);
//foreach to show the results
echo "Best picks:" . PHP_EOL . "<br />";
foreach ($heroPicks as $heroName => $pickCount) {
foreach ($heroVictory as $heroVictoryName => $totalVictory) {
$total = ($totalVictory * 100) / $pickCount;
}
echo $heroName . " - " . $pickCount . PHP_EOL . " - Victorys = " . $totalVictory . " -- winrate :" . $total . "%" . "<br />";
}
?>
@bassxzero 的 $result 变量
【问题讨论】:
-
你能发布这个文件是什么样子的吗
json_decode($file_contents) -
刚刚用新图片编辑了帖子