如何选择php循环中的第一个元素并对其应用类?

如何选择php循环中的第一个元素并对其应用类?,php,wordpress,Php,Wordpress,这是Wordpress中表的代码。我想在循环的第一个元素中添加一个类。我该怎么做呢。生成一系列td元素,如何更改代码,使类只添加到tr循环中的第一个td中 $table = get_field( 'hosting_plan_table' ); if ( $table ) { echo '<tbody>'; foreach ( $table['body'] as $tr ) { echo '<tr>'; foreach ( $tr as $

这是Wordpress中表的代码。我想在循环的第一个元素中添加一个类。我该怎么做呢。生成一系列td元素,如何更改代码,使类只添加到tr循环中的第一个td中

$table = get_field( 'hosting_plan_table' );

if ( $table ) {

echo '<tbody>';

foreach ( $table['body'] as $tr ) {

    echo '<tr>';

        foreach ( $tr as $td ) {

            echo '<td><span id="dottedunderlinet" class="'.$td['c'].'"> ';
                echo $td['c'];
            echo '</td>';
        }

    echo '</tr>';
}
$table=get_字段('hosting_plan_table');
若有($表){
回声';
foreach($tr形式的表格['body']{
回声';
foreach($tr as$td){
回声';
echo$td['c'];
回声';
}
回声';
}
您可以这样做

 if ( $table ) {

            echo '<tbody>';

                foreach ( $table['body'] as $tr ) {

                    echo '<tr>';

                      $class='first';

                        foreach ( $tr as $td ) {

                            echo '<td class="'.$class.'"><span id="dottedunderlinet" class="'.$td['c'].'"> ';
                                echo $td['c'];
                            echo '</td>';

                         $class='';
                        }

                    echo '</tr>';
                }
if($table){
回声';
foreach($tr形式的表格['body']{
回声';
$class='first';
foreach($tr as$td){
回声';
echo$td['c'];
回声';
$class='';
}
回声';
}

看看这个。我已经设置了一个名为
$I
的变量。在foreach循环中,我向
$I
添加1。这意味着循环第一次运行时,
$I
等于零。然后匹配
!$I
测试,并且可以将
$class
设置为要应用的类的名称

$table = get_field( 'hosting_plan_table' );

$i = 0;

if ( $table ) {

echo '<tbody>';

foreach ( $table['body'] as $tr ) {

    echo '<tr>';

        foreach ( $tr as $td ) {

            if(!$i) { $class = 'some-class'; } else { $class = ''; }

            echo '<td><span id="dottedunderlinet" class="'.$class.'"> ';
                echo $td['c'];
            echo '</td>';
        }

    echo '</tr>';

    $i++;

}
$table=get_字段('hosting_plan_table');
$i=0;
若有($表){
回声';
foreach($tr形式的表格['body']{
回声';
foreach($tr as$td){
如果(!$i){$class='some class';}其他{$class=''';}
回声';
echo$td['c'];
回声';
}
回声';
$i++;
}

您可以这样更新代码:

$counter = 0;
foreach ( $tr as $td ) {
  if($counter == 0){
    echo '<td class="my-custom-class-here"><span id="dottedunderlinet" class="'.$td['c'].'"> ';
  } else {
    echo '<td><span id="dottedunderlinet" class="'.$td['c'].'"> ';
  }
  echo $td['c'];
  echo '</td>';
  $counter++;
}
$counter=0;
foreach($tr as$td){
如果($counter==0){
回声';
}否则{
回声';
}
echo$td['c'];
回声';
$counter++;
}