胜率计算 - 来自 Leaguepedia 的 Php 和 api
Posted
技术标签:
【中文标题】胜率计算 - 来自 Leaguepedia 的 Php 和 api【英文标题】:Win Rate calculation - Php and api from leaguepedia 【发布时间】: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)
刚刚用新图片编辑了帖子
【参考方案1】:
外部的foreach
会循环显示你被选中的所有英雄。这就是你想要的。
内部foreach
循环遍历所有英雄的胜利,无论外部循环当前正在处理的英雄是什么。所有胜利都设置为 1,因为这是你胜利阵列中最后一个英雄的胜利数。这不是你想要的。
您不想要第二个内部foreach
。您只想查找当前由外部foreach
处理的英雄的胜利统计数据。
foreach ($heroPicks as $heroName => $pickCount)
$totalVictory = $heroVictory[$heroName] ?? 0;
$total = ($totalVictory * 100) / $pickCount;
echo $heroName . " - " . $pickCount . PHP_EOL . " - Victorys = " . $totalVictory . " -- winrate :" . $total . "%" . "<br />";
【讨论】:
以上是关于胜率计算 - 来自 Leaguepedia 的 Php 和 api的主要内容,如果未能解决你的问题,请参考以下文章