2016-02-28 21 views
1

我从我列出了使用foreach循环数据库的信息:腓选中的复选框从环

<table class="price_table"> 
    <caption>Prices</caption> 
    <?php if($price= getCarPricePeriod($car->ID)):?> 
     <?php foreach ($prices as $price): ?> 
      <tr> 
        <td><input type="radio" name="price" value="<?= $price['Price'];?>"> </td> 
       <td><?= $price['Price'];?>$</td> 
      </tr> 
     <?php endforeach; ?> 
    <?php endif; ?> 
</table> 

所以用这个循环,我得到的价格与单选按钮。如何使第一个项目从循环是checked。首先需要检查

如果我在循环中添加checked所有项目将被检查或随机。

+0

只需用一个计数器 –

回答

1

你将不得不使用一个变量标记你的元素是第一:

<table class="price_table"> 
    <caption>Prices</caption> 
    <?php if($price= getCarPricePeriod($car->ID)): 
     $first = true; 
     foreach ($prices as $price): ?> 
      <tr> 
        <td><input type="radio" name="price" value="<?= $price['Price'];?> <?= $first ? 'checked' : '' ?>"> </td> 
       <td><?= $price['Price'];?>$</td> 
      </tr> 
     <?php $first = false; 
     endforeach; ?> 
    <?php endif; ?> 
</table> 
1

快速的方法来做到这一点是有一个变量是标识符

<table class="price_table"> 
    <caption>Prices</caption> 
    <?php if($price= getCarPricePeriod($car->ID)):?> 
     <?php $checked=true; foreach ($prices as $price): ?> 
      <tr> 
       <td><input type="radio" name="price" value="<?= $price['Price'];?>"<?=$checked ? ' checked' : '';?>> </td> 
       <td><?= $price['Price'];?>$</td> 
      </tr> 
     <? $checked = false; ?> 
     <?php endforeach; ?> 
    <?php endif; ?> 
</table>