5
votes

Im using TCPDF, at the moment im a listing data in two columns using array_chunk which works fine. But i need data to be show in first columns and then second, see below:

Currently:
    1   2
    3   4
    5   6
    7   8
    9   10
Should be:
    1   6
    2   7
    3   8
    4   9
    5   10

This is the code:

<?php   $array = range(1, 50);?>
<table nobr="true" cellpadding="2">
     <?php foreach (array_chunk($array, 2) as $a) { ?>
        <tr>
        <?php foreach ($a as $array_chunk) { ?>
           <td><?php echo $array_chunk; ?></td>
            <?php
         } ?>
       </tr>
       <?php }    ?>
</table>

my second query(complex) if there are more than 30 rows i need to be able to use $pdf->AddPage(); and continues on the next page.

2
Have you attempted to solve this yourself? What was your approach? - Josef Engelfrost
@JosefEngelfrost , the only thing i tried so far is array_chunk code in the post. maybe array_slice would be a better apporach. im unsue about my second query though. - TheDeveloper

2 Answers

6
votes

TCPDF - support multicolumns, this is wat i used to solve my issue:

$pdf->AddPage();
$pdf->resetColumns();
$pdf->setEqualColumns(2, 84);  // KEY PART -  number of cols and width
$pdf->selectColumn();               
$content =' loop content here';
$pdf->writeHTML($content, true, false, true, false);
$pdf->resetColumns()

the code will add auto page break and continues to next page.

0
votes

I have not used PHP in a while, so I'll let you write the code, but hopefully this will help you tackle the problem.

I think you seconds problem is the easiest one: You can only have 30 rows per page. Since you have 2 items per row, that means 60 items per page. So simply split your array into arrays of 60 items per array, something like this, in pseudo code:

items = [1, 2, 3, ...] // an array of items
pages = []
i = 0
while 60 * i < items.length
    pages[i] = items.slice(i * 60, (i + 1) * 60)
    i = i + 1

The second problem is this: You want to create the output column per column, but HTML requires you to output it row per row. So, before we can output the row, we must know how many rows we want to output in total:

items = [1, 2, 3, ...] // an array of items
rows = items.length / 2 // The number of rows, make sure you round this right in PHP
n = 0
while n < rows
    // The n:th item of the first column
    print items[n]
    // the n:th item of the second column
    print items[rows + n]
    print "\n"
    n = n + 1

In your code you will probably have to check that items[rows + i] exists etc. Also make sure that rounding of odd numbers works the way you expect them to.