-1

我试图将复选框数组数据放入具有 3 列的表中。

我有一个名为的数组$a,其中包含从 A 到 Z 的 26 个数据。

然后我有另一个名为的数组$b,其中包含一些数据。

我想创建一个包含 26 个复选框的 3 列表,其中的数据位于 array 中$a

如果数据包含在 中$b,则选中其复选框,否则不选中。

以下是我的代码。我不知道如何格式化循环,以便复选框和表格正确显示。请帮忙。

<html>
<body>
<table>
<?php

$a = array("A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q","R","s","T","U","V","W","X","Y","Z");
$b = array("A","C","G","L","O","P","R","X","Z");
$a_size=count($a);

$tr=$a_size/3;
$reminder=$a_size%3;

if ($reminder!=0)
{
$tr+=1;
}

for($i=0;$i<$tr;$i++)
{
echo "<tr>";
foreach ($b AS $c)
{
    for($j=0;$j<3;$j++)
    {
        if(in_array($c,$b)) 
        {
            echo "<td><input name=\"system[]\" type=\"checkbox\" value=\"$c\" CHECKED> $c </td>";
        } 
        else
        {
            echo "<td><input name=\"system[]\" type=\"checkbox\" value=\"$c\"> $c </td>";
        }
    }
}   
echo "</tr>";
}
?>
</table>                                                
</body>
</html>                                                     
4

1 回答 1

2

我认为你让它有点过于复杂了!以下是我将如何处理这种情况:

<?php
    $a = array("A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
    $b = array("A","C","G","L","O","P","R","X","Z");
?>
<table>
    <?php foreach ($a as $k => $v) : ?>
    <tr>
        <td><?php echo $v; ?></td>
        <td><input type="checkbox" name="system[]" value="<?php echo $v; ?>" <?php if (in_array($v, $b)) echo 'checked'; ?> /></td>
        <!-- add as many td's here as you like -->
    </tr>
    <?php endforeach; ?>
</table>

这是“翻转”布局的另一种方法。

<?php
    $a = array("A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q","R","s","T","U","V","W","X","Y","Z");
    $b = array("A","C","G","L","O","P","R","X","Z");
?>
<table>
    <?php for ($i = 0; $i < 3; $i++) : ?>
    <tr>
        <?php foreach($a as $k => $v) : ?>
        <td><?php echo $v; ?><input type="checkbox" name="system[]" value="<?php echo $v; ?>" <?php if (in_array($v, $b)) echo 'checked'; ?> /></td>
        <?php endforeach; ?>
    </tr>
    <?php endfor; ?>
</table>

在我们在聊天中讨论后,我得到了您正在寻找的代码:

<table>
    <tr>
    <?php for($i = 1; $i < count($a); $i++) : $j = $i-1; ?>
        <td><?php echo $a[$j]; ?><input type="checkbox" name="system[]" value="<?php echo $a[$j]; ?>" <?php if (in_array($a[$j], $b)) echo 'checked'; ?> /></td>
        <?php if($i % 3 === 0) echo '</tr><tr>'; ?>
    <?php endfor; ?>
    </tr>
</table>
于 2012-12-08T08:26:50.760 回答