如何通过 PHPExcel 从第一行转换为带有键的数组


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

抱歉,找不到我需要的东西。我有 xls/xlsx。然后我得到这样的笑声:

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

第一行是带有值名称的标题。如何使PHPExcel转换为数组如下所示:

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

假设你已经在$array中拥有这个数组

$headings = array_shift($array);
array_walk(
    $array,
    function (&$row) use ($headings) {
        $row = array_combine($headings, $row);
    }
);

我的解决方案看起来像下面的代码。假设您已从电子表格中读取$rows

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

函数 toKeyedRows 指定如下:

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