简体   繁体   中英

Give Unique Class to each table row in loop

I have an PHP for loop; which looks at a number in database and outputs the tables rows to number of times.

Here is my HTML:

<?php
for($x=0; $x < 5; $x++){
$row_count =1;

  ?>
<table class="table table-bordered" id="ticktable">
<tr class=" <?php echo $row_count;  ?>">
<?php

for($w=0; $w < 5; $w++){

  ?>
<td>
     <img class="yellow-sign" src="http://www.backgroundsy.com/file/large/yellow-sign.jpg" width="100">
</td>
<?php

    }  
    ?>
    </tr>
  </table>
<?php
$row_count ++;
    }  
    ?>

The above code display this:

图片

How I can assign unique class to each of the rows?

Labelled Image

在此处输入图片说明

Example:

<?php foreach($data as $row) { ?>

    <tr id="data<?php echo $row['id']; ?>">   </tr>

<?php } ?>

I hope it will help you.

If you are trying to get unique class to tr then do this

for ($x = 0; $x < 5; $x++) {
$row_count = 1;
$randClass = rand(1111,9999).$row_count;
?>
<table class="table table-bordered" id="ticktable">
    <tr class="<?php echo $randClass; ?>">
        <?php

        for ($w = 0; $w < 5; $w++) {

            ?>
            <td>
                <img class="yellow-sign <?php echo $randClass; ?>" src="http://www.backgroundsy.com/file/large/yellow-sign.jpg" width="100">
            </td>
            <?php

        }
        ?>
    </tr>
</table>
<?php
$row_count++;
}

rand(1111,9999) will generate random number between 1111 and 9999
EDIT

i have also added $row_count so that the number can not be repeated even if there is large data. What I've done is: <tr class="<?php echo rand(1111,9999).$row_count; ?>">

UPDATE
first store the random string in a variable $randClass = rand(1111,9999).$row_count;
then echo out where you want the variable like this:
$randClass = rand(1111,9999).$row_count;
and
<img class="yellow-sign <?php echo $randClass; ?>" >

Here is the updated code for you. Check this

 <?php
    $color_class[] = array("yellow-sign","red-sign","green-sign","blue-sign","black-sign");
    $row_count = 0;
    for($x=0; $x < 5; $x++){


 ?>

    <table class="table table-bordered" id="ticktable">
    <tr class=" <?php echo $row_count;  ?>">
 <?php

    for($w=0; $w < 5; $w++){

  ?>
    <td>
         <img class="<?php echo $color_class[$row_count];  ?>"
          src="http://www.backgroundsy.com/file/large/yellow-sign.jpg" width="100">
    </td>
 <?php

        }  
  ?>
        </tr>
      </table>
 <?php
    $row_count ++;
        }  
 ?>

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