Newbie Newbie - 1 month ago 6
PHP Question

How to format array data in a table with specified number of column?

I tried to put check box array data into table with 3 columns.

I have an array named

$a
which contains 26 data, from A to Z.

Then I have another array named
$b
which contains some data.

I want to create a 3-columns table with 26 check boxes with the data in array
$a
.

if the data is contained in
$b
, its checkbox will be checked otherwise it's unchecked.

The following is my code. I have no idea how to format the loop so the checkboxes and table will show correctly. Please help.

<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>

Answer

I think you're making it a little overcomplicated! Here's how I would approach this situation:

<?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>

Here's an alternative way to "flip" the layout.

<?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>

After our discussion in chat I have the code you're looking for:

<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>
Comments