使用PHP

时间:2017-05-03 13:03:47

标签: php text-files

如前所述,我是PHP编码的初学者。我已经制作了一个文本文件,其中包含我的学生信息,如下所示 - 这包括他们的姓名,科目标记,电子邮件地址和注册日期:

Ann Thompson:50,90,82,64,75:ann@amuniversity.com:2016-02-01

Jeremiah Hanson:80,75,88:jeremiah@amuniversity.com:2016-03-02

比利·琼斯:89,72,46,54:billy@amuniversity.com:2016-04-12

我还创建了一个表单,该表单输入一个字段,该字段包含用户希望读取的文件名以及用户希望写入的文件名字段。

我从哪里开始获取下面的输出?

学生摘要:

  • Ann Thompson注册于2016-02-01,平均48人,符号F。

  • Jeremiah Hanson报名参加....

  • Billy Jones参加了....

它还应该在上次修改时显示底部的日期。

请帮助

1 个答案:

答案 0 :(得分:0)

请检查以下代码。我在任何我认为需要的地方评论了代码。如果你不理解它,请告诉我。显然,您需要根据您的成绩系统更新checkGrade功能,但您明白了这一点:)

<?php
// Read the input file line by line into "input" array
$filename = "input.txt";
$input = explode("\n", file_get_contents($filename));

// Go through each line
for($i = 0; $i < sizeOf($input); $i++){

    // split line by :
    $line = explode(":", $input[$i]);

    // Initialize variables based on position
    $name = $line[0];
    $numbers = $line[1];
    $email = $line[2];
    $registration = $line[3];

    // Calculate average
    // Remove any spaces first from the numbers
    $numbers = str_replace(' ', '', $numbers);
    // Split the numbers by ,
    $numbersArray = explode(",", $numbers);
    $sum = 0;
    // Calculate sum
    for($j = 0; $j < sizeOf($numbersArray); $j++){
        $num = (int)$numbersArray[$j];
        $sum += $num;
    }
    $avg = $sum/sizeof($numbersArray);

    // Print it
    echo "$name enrolled in $registration, has an average of $avg, with a symbol ". checkGrade($avg) ."<br>";

}

// Last modified date of the input file
echo "<br><br><br>";
if (file_exists($filename)) {
    echo "This file was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

function checkGrade($num){
    if ($num < 65){
        $grad = 'F';
    }
    else if ($num<= 66 && $num >=65){
        $grad = 'D';
    }
    else if ($num <= 69 && $num >=67){
        $grad = 'D+'; 
    }
    else if ($num <= 73 && $num >=70){
        $grad = 'C-';
    }
    else if ($num <= 76 && $num >=74){
        $grad = 'C';
    }
    else if ($num<= 79 && $num >=77 ){
        $grad = 'C+';
    }
    else if ($num <= 83 && $num >=80){
        $grad = 'B-'; 
    }
    else if ($num <= 86 && $num >=84){
        $grad = 'B';
    }
    else if ($num <= 89 && $num >=87){
        $grad = 'B+';
    }
    else if ($num <= 93 && $num >=90){
        $grad = 'A-';
    }
    else if ($num <= 96 && $num >=94){
        $grad = 'A';
    }
    else if ($num >= 97){
        $grad = 'A+';
    }
    return $grad;
}
?>

这是输出:

Ann Thompson enrolled in 2016-02-01, has an average of 72.2, with a symbol C-
Jeremiah Hanson enrolled in 2016-03-02, has an average of 81, with a symbol B-
Billy Jones enrolled in 2016-04-12, has an average of 65.25, with a symbol D



This file was last modified: May 03 2017 13:12:13.