Home » excel » php – How to convert to array with keys from first row by PHPExcel?

php – How to convert to array with keys from first row by PHPExcel?

Posted by: admin March 9, 2020 Leave a comment

Questions:

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
How to&Answers:

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);
    }
);

Answer:

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;
}