2

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

3 Answers 3

5

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>";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

4
$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>';

Comments

-1

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]

3 Comments

You're closing table tag should be outside of the foreach loop. Also you don't handle the case where count($input) % $cols != 0.
Didn't you forget to increment $i?
I did forget to increment $i, fixed it. @Brian Fisher: I have picked up with HTML, that if there is two columns and at the last row there is only one <td>, then it would be sorted into the first column and the second one left blank (one that row). Thus the reason I left out that exception handling

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.