1

I have the following loop:

for($column = 'A'; $column != $lastColumn; $column++) {
          for ($row = 2; $row <= 6; $row++) {
              $cell[] = $objWorksheet->getCell($column.$row)->getFormattedValue();
              if($column == 'A') {
                $arrayTeste = array('A' => $cell);
              } else {
                $arrayTeste = array('B' => $cell);
              }
          }
      }

What I want is: I want to make a new array with key 'A' using the values in 'cell' array. Because in another part of my code I need to echo just the values inside 'A' key. Like when you echo from a DB index. Example: echo $array['A']. Also in this second part, I'll need a foreach to print all the array, right?

4
  • that's not going to work. you keep overwriting arrayTeste on every loop iteration, and will end up with only the LAST value when both loops exit. Commented Jun 13, 2016 at 20:19
  • please, show an example and I'll help you Commented Jun 13, 2016 at 20:28
  • Why don't you just use the rangeToArray() method that's already buit into PHPExcel? Commented Jun 13, 2016 at 20:42
  • Thank you all for the tips. With the reply of Felippe I was able to do the work. Commented Jun 14, 2016 at 11:38

2 Answers 2

2

The problem with your current code is that you are going to be overwriting $arrayTeste each time you go through the loop. This can be solved with a multidimensional array as follows:

if($column == 'A') {
    $arrayTeste[$column][$row] = array('A' => $cell);
} else {
    $arrayTeste[$column][$row] = array('B' => $cell);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just put your data inside an array, indexed by your column:

$cell = [];
for($column = 'A'; $column != $lastColumn; $column++) {
    for ($row = 2; $row <= 6; $row++) {
        $cell[$column][] = $objWorksheet->getCell($column.$row)->getFormattedValue();
    }
}

Output will be something like:

['A'] =>
   [0] => 'cella1',
   [1] => 'cella2',
['B'] =>
   [0] => 'cellb1',
   [1] => 'cellb2',
 ...

Comments

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.