在每个循环中回显 div class 'last'

echo div class 'last' in for each loop

大家早上好。 只是 foreach 循环有点问题,我在其中回显 div class="related-product', and would like to target the last div, to a 'class=" 相关产品最后一个。

<?php 
$relatedProd = explode(';', $row['relatedProd']);

if (sizeof($relatedProd) > 0) {
    echo '<h4>Hello World!</h4>';
}
foreach ($relatedProd as $key => $value) {
    echo '<div class="one_third product-table <?php
    if ( $key == ( count( $relatedProd ) -1 ) ) echo
    last ">';

    echo '</div>';
}
?>

这将通过直接在 php 循环中分配值来完成工作,而无需 <?php 标签:

$lastStr = "";
foreach ($relatedProd as $key => $value) {
    if ($key == count($relatedProd)-1) {
        $lastStr = " last";
    }
    echo "<div class=\"one_third product-table{$lastStr}\"></div>";
}

试试这个,首先它更容易阅读,因此维护和调试,而且你不需要在 PHP 块中启动另一个 <?php

<?php 
   $relatedProd = explode(';', $row['relatedProd']);

   if (sizeof($relatedProd) > 0) {
      echo '<h4>Hello World!</h4>';
   }
   foreach ($relatedProd as $key => $value) {
      $extra = $key == count( $relatedProd ) -1 ? 'last' : '';
      echo '<div class="one_third product-table ' . $extra . '"></div>'; 
   }
?>