8

Sorry, cant find what i need. I have xls/xlsx. Then i get smth like this:

array
  0 => 
    array
    0 => string 'NameFirstColumn'
    1 => string 'NameSecondColumn'
  1 => 
    array
    0 => string 'qqq'
    1 => float 30
  2 => 
    array
    0 => string 'www'
    1 => float 20

First row is a header with names of values. How to make PHPExcel convert to array looks like:

array
  0 => 
    array
    NameFirstColumn => string 'qqq'
    NameSecondColumn => float 30
  1 => 
    array
    NameFirstColumn => string 'www'
    NameSecondColumn => float 20
Philipp Klemeshov
  • 383
  • 1
  • 5
  • 14

2 Answers2

19

Assuming that you already have this array in $array

$headings = array_shift($array);
array_walk(
    $array,
    function (&$row) use ($headings) {
        $row = array_combine($headings, $row);
    }
);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

My solution look like the code below. Assuming that you have read the $rows from the spreadsheet

$header = array_shift($rows); 
$data = toKeyedRows($rows, $header);

The function toKeyedRows is specified like below:

function toKeyedRows(array $rows, array $header) : array
{       
  array_walk($header,function($value,$key){ $value = $value?:$key; });

  array_walk(
      $rows,
      function(&$row)use($header)
      {
        $row = array_combine($header,$row);
      }
  );

  return $rows;
}
Mark Baaijens
  • 496
  • 5
  • 6