duanpao9781 2018-09-04 00:33
浏览 60
已采纳

如何根据用户输入从csv读取

I have a csv file containing European football team results. I wish for users to enter a team and then the system to display the results for that team including losses.

I managed to read the csv file with php.

How do read team names from users of the program?

How do I query the CSV file so as to retrieve results for that team?

Read data from http://www.football-data.co.uk/mmz4281/1718/I1.csv (Italy Football Results, Season 2017/2018, results; match stats; match, total goals)

This is my code so far in 2 files:

<?php

include('init.inc.php');
header('Content-type: text/plain');
print_r(read_csv('I1.csv'));
$data = read_csv('I1.csv');

<?php

function read_csv($filename){
    $rows = array();

    foreach (file($filename, FILE_IGNORE_NEW_LINES)as $line){
      $rows[] = str_getcsv($line);
    }

    return $rows;
}

function write_csv($filename, $rows){
    $file = fopen($filename, 'w');

    foreach ($rows as $row){
        fputcsv($file, $row);
    }
    fclose($file);

}
  • 写回答

1条回答 默认 最新

  • dongliugu8843 2018-09-04 02:23
    关注

    Football coding:

    The problem is not so hard but first you need to understand the codes in the CSV.

    These can be found here: http://www.football-data.co.uk/notes.txt and is based on home and away games. For example, if you pick a team like Juventus in the first row, you can see they played at Home and the final result "FTR" is "H" meaning they won that match.

    You need to get your head around the CSV coding before you can write any PHP!

    EDIT: Changed implementation on request of requester to operate as a single HTML file.

    Assuming you have a web server set up, that is PHP enabled, you can coy-paset the code below into a file and run in in browser. In my case I called the file test.php and run it by typing the URL localhost:8080/test.php in the browser. You need to have the 2 files test.phpand Results.csv located at your website home directory. I have IISExpress browser running which listens at port 8080.

    EDIT: Added losses breakdown at request of asker.

    <!DOCTYPE HTML>  
    <html>
    <body> 
    <head> 
    <style>
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
    </style>
    <head>
    
    <?php
    // define variables and set to empty values
    $teamIn  = "";
    $homeLosses = 0;
    $awayLosses = 0;
    $totalLosses = 0;
    $winningTeams = []; // list of winning teams
    
    if ( !($_SERVER["REQUEST_METHOD"] == "POST") )
    {  // we reach here only if form was not submitted yet
            $teamIn  = "None";
            $homeLosses = 0;
            $awayLosses = 0;
            $totalLosses = 0;
            $winningTeams = []; 
    } 
    else
    {   // we arrive here only if form is submitted
    
        $teamIn = ucfirst($_POST["teamName"]);  // make first char of teamname a capital
    
        //---------------------------------------------------------------------------
        // First read the CSV file and make an associative array based on first row titles
        //------------------------------------------------------------------------------
        $fileName = "Results.csv";    // CSV File name changed to "Results.csv" 
        $teams = $fields = array(); $i = 0;
        $handle = fopen($fileName, "r");
        if ($handle) {
            while (($row = fgetcsv($handle, 4096)) !== false) {
                if (empty($fields)) {
                    $fields = $row;
                    continue;
                }
                foreach ($row as $k=>$value) {
                    $teams[$i][$fields[$k]] = $value;
                }
                $i++;
            }
            if (!feof($handle)) {
                die("Error: unexpected fgets() fail
    ");
            }
            fclose($handle);
        }
        else{
            die("Did not open file: ".$fileName.PHP_EOL);
        }    
    
    
        //---------------------------------------------------------------------------
        //  now make a list of losses and make a list of teams that have beaten the team entered.
        //------------------------------------------------------------------------------
        $n = 0;
        foreach ($teams as $team){
            if ( $team['HomeTeam'] == $teamIn ){
                if ($team['FTR'] == "A" ) {
                     $homeLosses++;
                     $winningTeams[$n]['date'] = $team['Date'];
                     $winningTeams[$n]['name'] = $team['AwayTeam'];
                     $winningTeams[$n]['location'] = "at Home";
                     $winningTeams[$n]['goalsFor'] = $team['FTAG'];
                     $winningTeams[$n]['goalsAgainst'] = $team['FTHG'];
                     $n++;
                }
            }
            else if  ($team['AwayTeam']== $teamIn){
                if ($team['FTR'] == "H" ) {
                    $awayLosses++;
                    $winningTeams[$n]['date'] = $team['Date'];
                    $winningTeams[$n]['name'] = $team['HomeTeam'];
                    $winningTeams[$n]['location'] = "away";
                    $winningTeams[$n]['goalsFor'] = $team['FTHG'];
                    $winningTeams[$n]['goalsAgainst'] = $team['FTAG'];
                    $n++;
                }    
            }
          }
          $totalLosses = $homeLosses+$awayLosses;
    
    }
    // end of PHP section
    ?>
    
    <!–- This part is the form to enter your team --->
    <!–- We submit the form to self- meaning this file --->
    <h2>Get Match Results</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
       Enter Team Name: <input type="text" name="teamName">
      <input type="submit" name="submit" value="Submit">  
    </form>
    
    <!–- This part prints out losses summary --->
    <?php
    echo "<h2>".$teamIn."</h2>";
    echo "<p><b>Summary of Losses</b></p>";
    echo "<table>";
    echo "  <tr>";
    echo "    <th>Team</th>";
    echo "    <th>Away Losses</th> ";
    echo "    <th>Home Losses</th>";
    echo "    <th>Total Losses</th>";  
    echo "  </tr>";
    echo "  <tr>";
    echo "    <td>".$teamIn."</td>";
    echo "    <td>".$awayLosses."</td> ";
    echo "    <td>".$homeLosses."</td> ";
    echo "  </tr>";
    echo "</table>";
    ?>
    <!–- This part prints out list of teams who beat the entered team --->
    <?php
    echo "<p><b>Details of losses</b></p>";
    echo "<table>";
    echo "  <tr>";
    echo "    <th>Beaten By</th>";
    echo "    <th>Date</th> ";
    echo "    <th>Location</th>";
    echo "    <th>Goals For</th>";
    echo "    <th>Goals Against</th>"; 
    echo "  </tr>";
        foreach ($winningTeams as $winningTeam){
            echo "  <tr>";
            echo "    <td>".$winningTeam['name']."</td>";
            echo "    <td>".$winningTeam['date']."</td>";
            echo "    <td>".$winningTeam['location']."</td>";  
            echo "    <td>".$winningTeam['goalsFor']."</td>"; 
            echo "    <td>".$winningTeam['goalsAgainst']."</td>";     
            echo "  </tr>";
        }
    echo "</table>";
    ?>
    
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据