簡體   English   中英

PHP:多個arrays放入html表

[英]PHP : multiple arrays into html table

我有這段代碼,我想將兩個 arrays 提交到 html 中的一個表中。它工作正常,直到我嘗試將另一個數組添加到表中。

在此處輸入圖像描述這是我添加下一個要在可能的分數列中顯示的數組之前的樣子。 添加新數組后,所有行都消失了,但剩下列標題。 如果可能的話,我想保持與目前所做的相同的格式。

<!DOCTYPE html>
<html>
<body>
<table border="1">

<th></th><th>Student Score</th><th>Possible Score</th><th>Percentage</th>

<?php
//Scores to table
    $Scores = fopen("scores.txt", "r");
    $Poss = fopen("Poss.txt", "r");
    $ind = 0;
    
    while(!feof($Scores)) {
        $Scoresarray[$ind] = fgets($Scores);
        $ind++;
    }
    while(!feof($Poss)) {
        $Possarray[$ind] = fgets($Poss);
        $ind++;
    }

    fclose($Poss);
    fclose($Scores);
    
    if(sizeof($Scoresarray,$Possarray)>1){
        $i=1;
        while($i<sizeof($Scoresarray,$Possarray)){
            echo "<tr>
            <td>".$i."</td>
            <td>".$Scoresarray[$i-1]."</td>
            <td>".$i."</td>
            <td>".$Possarray[$i-1]."</td>
            </tr>";
            
            $i++;
        }
    }


?>

</table>
</body>
</html>

假設 2 arrays 的長度相同,你可以做......

所有計數器都可以刪除,不需要它們, sizeof()一次只會計算一個數組,並且是count() function 的別名,所以我使用了count()

如果你使用foreach()來獲取一個數組的出現和索引,就像這樣foreach ($Scoresarray as $i => $score ){你可以遍歷 arrays 中的一個並使用索引獲取相應的其他陣列的出現也是如此。

$Scores = fopen("scores.txt", "r");
$Poss = fopen("Poss.txt", "r");

while(!feof($Scores)) {
    $Scoresarray[] = fgets($Scores);
}
while(!feof($Poss)) {
    $Possarray[] = fgets($Poss);
}

fclose($Poss);
fclose($Scores);

if( count($Scoresarray) > 1 && count($Possarray) > 1){
    foreach ($Scoresarray as $i => $score ){
        echo "<tr>
        <td>".$i."</td>
        <td>".$score."</td>
        <td>".$i."</td>
        <td>".$Possarray[$i]."</td>
        </tr>";
    }
}

再次假設文件的長度相同,您可以構建一個 Assoc 值數組,這樣結果的處理就變得更加容易

$Scores = fopen("scores.txt", "r");
$Poss = fopen("Poss.txt", "r");

while(!feof($Scores)) {
    $scoreAndPos[] = ['score' => fgets($Scores), 'Poss' =>fgets($Poss)];
}

foreach ($scoreAndPos as $i => $sp ){
    echo "<tr>
    <td>".$i."</td>
    <td>".$sp['score']."</td>
    <td>".$i."</td>
    <td>".$sp['poss']."</td>
    </tr>";
}

或者您可以使用file()將整個文件讀入行數組。

$Scores = file("scores.txt");
$Poss = file("Poss.txt");

然后使用第一個 foreach 循環來處理這些 2 arrays

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM