1

How can I loop multidimensional array in PHP Excel?

This is my code

$objWorkSheet = $this->excel->createSheet(1); //Setting index when creating
    $colors = array(
        array("A1", "B1", "C1", "D1"),
        array("A2", "B2", "C2", "D2"),
        array("A3", "B3", "C3", "D3")
    );

    $i = 2;
    foreach ($colors as $values) {
        $objWorkSheet->setCellValue('A'.$i++, $values[0]);
        $objWorkSheet->setCellValue('B'.$i++, $values[1]);
        $objWorkSheet->setCellValue('C'.$i++, $values[2]);
        $objWorkSheet->setCellValue('D'.$i++, $values[3]);
    }

But it gives me this result

enter image description here

What I want is A2 - D2 will loop horizontally then next will A3 - D3 then so on and so forth

already read this foreach multidimensional array but still cant get it.

Community
  • 1
  • 1

1 Answers1

2

Every $i++ increments the value of $i. In the first loop, all the values should be put in the 2nd row then 3rd and so on. So you need to increment the value after the values are put in the respective cell. Try -

foreach ($colors as $values) {
    $objWorkSheet->setCellValue('A'.$i, $values[0]);
    $objWorkSheet->setCellValue('B'.$i, $values[1]);
    $objWorkSheet->setCellValue('C'.$i, $values[2]);
    $objWorkSheet->setCellValue('D'.$i, $values[3]);
    $i++;
}
Ranjul Arumadi
  • 109
  • 1
  • 2
  • 11
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87