0

how to achieve the following table in excel or HTML.

+----+----+----+----+----+----+----+----+----+----+----+----+
|a   |b   |c   |a   |b   |c   |a   |b   |c   |a   |b   |c   |
+----+----+----+----+----+----+----+----+----+----+----+----+

EDIT FOR REAL CASE:

So I want to print Rit, Liter, and Volume respectively in ms Excel for about 15 times. let say Rit will occupy column E1, Liter on F1, Volume G1..repeat 15 times.

heres is my code so far:

$i = 0;
$j = 1;
foreach($this->cellRange('E', 'AY') as  $col){
    if($i % 3 == 2){
        if($j > 15){
            $sheet->setCellValue($col.'5', 'Total');
        }else{
            $sheet->setCellValue($col.'5', $j);
        }
        $sheet->setCellValue($col.'6', 'Volume');
        $j++;
    }else if($i % 2 == 1){
        $sheet->setCellValue($col.'6', 'Liter');
    }else{
        $sheet->setCellValue($col.'6', 'Rit');
    }

    $i++;
}

$this refer to current object (Laravel controller), while $sheet refer to PHPExcel sheet object.

Dariel Pratama
  • 1,607
  • 3
  • 18
  • 49
  • The loop you showed will loop 11 times (not 12 as you apparently want), but it does nothing more than loop. Can you edit the code to show where you're attempting to print output? – user2740650 Apr 04 '21 at 16:18

1 Answers1

0

After edit:

Since you're using $this->cellRange('E', 'AY') to loop over your range, you can keep track of a counter (like you've already got).

However, instead off using modulus, I would just create a hard-coded check, something like so:

<?php

$i = 0;
foreach($this->cellRange('E', 'AY') as  $col){

    // Handle 1/2/3
    switch ($i) {
        case 1:
            $sheet->setCellValue($col.'5', 'Total');
            break;

        case 2:
            $sheet->setCellValue($col.'6', 'Volume');
            break;

        case 3:
            $sheet->setCellValue($col.'6', 'Rit');
            break;
    }

    // Add 1 to $i, If ($i === 3), start over by setting to 1
    $i = ($i === 3) ? 1 : ++$i;
}

Before edit:

We can use PHP's ability to increment characters so simplify this like so:

<?php

for($i = 0; $i <= 3; $i++){
    for($c = 'a'; $c <= 'c'; $c++){
        echo $c;
    }
}
abcabcabcabc

Try it online!


We could also use PHP's range() to generate a range for us.

<?php
$res = [];
for($i = 0; $i <= 3; $i++){
    $res = array_merge($res, range('a', 'c'));
}

echo implode('', $res);

Try it online!

0stone0
  • 34,288
  • 4
  • 39
  • 64