简体   繁体   中英

Toggle class name in PHP

I am trying to stripe a table based on the time in each row. For example:

Blah -  time 1
Blah2 - time 1
Blah3 - time 2
Blah4 - time 3
Blah5 - time 4 

I need time 1 to be one colour (blue for example) time 2 to be colour black, time 3 to toggle back blue. I am trying to toggle the colour changed based on when the time has changed. My PHP so far:

    while($main_Row = $main_Results->fetch_assoc()){
        if( $pickup_Time == $main_Row['pickup_Time'] ){
            $stripe = "blue";   
        }
        else{
            $stripe = "black";  
            $pickup_Time = $main_Row['pickup_Time'];
        }

        echo '<tr class="'.$stripe.'">';
        echo '<td>Blah'.$i.'</td>';
        echo '<td>'.$main_Row['pickup_Time'].'</td>';
        echo '</tr>';
    }

What I have currently is not giving me the results I desire. I feel I'm missing something, any help would be greatly appreciated.

$pickup_Time = "";
$stripe = "";
while($main_Row = $main_Results->fetch_assoc()){
    if( $pickup_Time != $main_Row['pickup_Time'] ){
        $stripe = $stripe == "blue" ? "black" : "blue";   
    }

    echo '<tr class="'.$stripe.'">';
    echo '<td>Blah'.$i.'</td>';
    echo '<td>'.$main_Row['pickup_Time'].'</td>';
    echo '</tr>';

    $pickup_Time = $main_Row['pickup_Time'];
}

Quickly threw something together, it's a little verbose, but I wanted to make the general intent and process clear.

This will stripe per row, to stripe per column you would add your classes onto the td. If you want to change how many stripes before it cycles over again, change the modulo to whatever number you want.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>

        <style>
            .red {
                background-color: red;
            }

            .blue {
                background-color: blue;
            }
        </style>
    </head>
    <body>
        <?php

        $mysqli = new mysqli('', '', '', '');

        $qry = "SELECT * FROM data";
        $result = $mysqli->query($qry);

        $counter = 1;

        echo "<table>";
        while ( $row = $result->fetch_assoc() ) {

            $class = "";
            if( $counter % 3 == 1 ) {
                $class = "blue";
            } else if ( $counter % 3 === 2 ) {
                $class = "red";
            }

            echo '<tr class="' . $class . '">';
            echo '<td>' . $row['id'] . '</td>';
            echo '<td>' . $row['id'] . '</td>';
            echo '<td>' . $row['id'] . '</td>';
            echo '</tr>';

            $counter += 1;
        }
        echo "</table>";

        $result->free();

        $mysqli->close();
        ?>
    </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM