Caballero
Caballero

Reputation: 12101

Generating HTML table from PHP array

I don't understand this. I need to solve seemingly simple problem, and yet it's beyond my logic. I need to write a function: table_columns($input, $cols) which would output a table(example):

$input = array('apple', 'orange', 'monkey', 'potato', 'cheese', 'badger', 'turnip');
$cols = 2;

Expected output:

<table>
  <tr>
    <td>apple</td>
    <td>cheese</td>
  </tr>
  <tr>
    <td>orange</td>
    <td>badger</td>
  </tr>
  <tr>
    <td>monkey</td>
    <td>turnip</td>
  </tr>
  <tr>
    <td>potato</td>
    <td></td>
  </tr>
</table>

Upvotes: 2

Views: 4716

Answers (3)

Pangolin
Pangolin

Reputation: 7444

Try this function:

function table_columns($input, $cols)
{
    int $i = 0;
    echo "<table><tr>";
    foreach ( $input as $cell )
    {
        echo "<td>".$cell."</td>";
        $i++;
        if($i == $cols)
        {
            $i = 0;
            echo "</tr><tr>";
        }
    }
    echo "</tr></table>";
}

I hope it solves your problem.

[EDIT: Fixed the mistakes, was in a hurry]

Upvotes: -1

nickf
nickf

Reputation: 546005

Think about it like this. Say you have an array of items like this:

a, b, c, d, e, f, g, h, i, j, k

With columns set to 2, you'd need to render them in this order:

a  g
b  h            0 6 1 7 2 8 3 9 4 10 5
c  i      --->  a g b h c i d j e  k f
d  j
e  k
f

With three columns:

a  e  i
b  f  j        0 4 8 1 5 9 2 6 10 3 7
c  g  k   ---> a e i b f j c g  k d h
d  h

So, roughly:

function cells ($input, $cols) {

  $num = count($input);
  $perColumn = ceil($num / $cols);

  for ($i = 0; $i < $perColumn; $i++) {

     echo "<tr>";

     for ($j = 0; $j < $cols; $j++) {
        // you'll need to put a check to see you haven't gone past the
        // end of the array here...

        echo "<td>" . $input[$j * $perColumn + $i] . "</td>";
     }
     echo "</tr>";
  }
}

Upvotes: 5

Danzan
Danzan

Reputation: 968

$input = array_chunk($input, $cols);
$html = '<table>';
foreach($input as $tr){
    html .= '<tr>';
    for($i = 0; $i < $cols; $i++) $html .= '<td>'.(isset($tr[$i]) ? $tr[$i] : '').'</td>';
    $html .= '</tr>';
}
$html .= '</table>';

Upvotes: 4

Related Questions