Foreach with Table - PHP 和 Leaguepedia API

问题描述

我有这个代码显示一个冠军在锦标赛中被选中的次数(例如“Gragas:2次”、“Syndra:4次”等)

我正在使用 Leaguepedia 的 api 来接收信息

但我现在卡住了,我在“回显”我的表格以显示结果时遇到了问题。 所以我希望“qtd”位于“pick”一侧(Image1),如果有一种简单的方法可以显示我想要的东西。

// $Result is a CURL coming from leaguepedia api
$result = json_decode($file_contents);

// Double foreach to access the values from leaguepedia api
foreach ($result as $d) {
    foreach ($d as $data) {
        // $data->title->Team1Picks  is coming from league pedia api as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
        // So I need to explode to an array to count.
        $picks[] = explode(",",$data->title->Team1Picks);
    }
}

// $mostpicked is an array for me to count how many times a champion was picked
// $f is an array to see the names of the picked champions
foreach ($picks as $pick) {
    foreach ($pick as $total) {
        $mostPicked[] = $total;
        $f[] = $total;
    }
}

// Basically here I'm  counting how many times a champion was picked Ex : ("Gragas:2","Syndra:4",etc)     
asort($mostPicked);

$mostPicked = array_count_values($mostPicked);

$name = array_unique($f);

asort($name);

// Foreach to get all unique names from the picks Ex : ("Gragas","Shen",etc) instead of ("Gragas,"Gragas",etc)
foreach ($name as $champ) {
    echo "<tr>";
    echo "<td>" . $champ . "</td>";
    echo "</tr>";
}

// This foreach to get the number of times a pick was made Ex : ("Gragas 2 Times")
foreach ($mostPicked as $pick) {    
    echo "<tr>";
    echo "<td>" . $pick . "</td>";   
    echo "</tr>";
}

enter image description here

解决方法

这似乎是因为您将 $pick 放入新的 <tr>

尝试调整循环,以便构建一个 $champ=>$qtd 数组,然后对其进行迭代并根据需要构建表。

,

给你,这个应该可以。

// Hero name => pick count
$heroPicks = array();
foreach ($result as $d) {
    foreach ($d as $data) {
        //$data->title->Team1Picks  is coming from league pedia api as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
        // So i need to explode to an array to count.
        $picks = explode(",",$data->title->Team1Picks);
        foreach ($picks as $pick) {
            $pick = trim($pick);
            if (!array_key_exists($pick,$heroPicks)) {
                $heroPicks[$pick] = 0;
            }
            $heroPicks[$pick] += 1;
        }
    }
}

uasort($heroPicks,function($a,$b) {
    return $a - $b;
});
$heroPicks = array_reverse($heroPicks);

echo "Best picks:".PHP_EOL."<br />";
foreach ($heroPicks as $heroName => $pickCount) {
    echo $heroName." - ".$pickCount.PHP_EOL."<br />";
}