dm90
dm90

Reputation: 795

Get column, row label of a table in PHP

I need to get those who has more than 15 points in particular time and show in HTML page (table), the data is loaded from a CSV. The CSV file looks like below:

test.csv file

Name,Sun 0:00,Sun 1:00,Sun 2:00,Sun 3:00,Sun 4:00
John,2,0,0,0,16
Alex,0,0,0,0,0
Dan,0,15,0,0,0
Jeff,0,0,30,0,0
Peter,12,0,0,0,0
Joe,0,0,0,0,340
Bill,0,0,340,0,0`

Here is the PHP file which process the CSV and shows in HTML table.

<html>
<body>
<?php
echo "<html><body><table>\n\n";
echo "<style>\ntable,th,td\n{\nborder:1px solid black;\nborder-collapse:collapse\n}\n</style> ";
$f = fopen("test.csv", "r");
while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    foreach ($line as $cell) {
            if ($cell >=15)
            echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>
</body>
</html>`   

But this code only provides the output as like below without the column, row label. The second table is what I'm expecting in the output.

enter image description here

PS: If this is can be done in jQuery/Javascript, those ideas also welcome.

Upvotes: 0

Views: 272

Answers (2)

ildanno
ildanno

Reputation: 119

Ignoring the wrong markup (you duplicate some tags), your error is that you print a cell only if the value is greater than 15. You must print always the cell instead, and print content only if it is gt 15. Example:

<html>
    <body>
    <style>
    table,th,td
    {
        border: 1px solid black;
        border-collapse:collapse;
    }
    </style>
    <table>
    <?php
    $f = fopen("test.csv", "r");
    $i = 0;
    while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        $j = 0;
        foreach ($line as $cell) {
            echo "<td>";
            if ($i==0 || $j==0 || $cell >= 15) {
                echo htmlspecialchars($cell);
            }
            echo "</td>";
            $j++;
        }
        echo "</tr>";
        $i++;
    }
    fclose($f);
    ?>
    </table>
    </body>
</html>

Upvotes: 1

asprin
asprin

Reputation: 9833

if ($cell >=15) will fail for anything that is not an integer. Hence, all string values are ignored

Instead of that use

 if (trim($cell) != '')

Upvotes: 0

Related Questions