1

I am working with php spreadsheet library and was able to get the multi dimensional array of sheet data. but now I want to convert this array to an associative array by using first row of sheet as keys.

    $arr_upsfile = explode('.', $_FILES['upsfile']['name']);
    $extension_ups = end($arr_upsfile);
    if('csv' == $extension_ups){
        $reader_ups = new \PhpOffice\PhpSpreadsheet\Reader\Csv();

    }elseif('xls' == $extension_ups){
        $reader_ups = new \PhpOffice\PhpSpreadsheet\Reader\Xls();

    }else {
        $reader_ups = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
     
    }
    $spreadsheet_ups = $reader_ups->load($_FILES['upsfile']['tmp_name']);
    $sheetData_ups = $spreadsheet_ups->getActiveSheet()->toArray();

   for($i=0;$i<count($sheetData_ups);$i++)
    {
        for($j=0;$j<count($sheetData_ups[0]);$j++)
        {
            if($i==0)
            {
                $columns[$j] = $sheetData_ups[$i][$j]; //getting columns name in array
            }
                    //tried pushing sheet array rows to dynamic keys from columns array
                    $ups[$i] = array(
                    " $columns[$j]" =>  $sheetData_ups[$i][0] );                  );

        }  
        
    }

    var_dump($ups);
Alex
  • 23
  • 2

1 Answers1

2

You can do this with little changes;

 $arr_upsfile = explode('.', $_FILES['upsfile']['name']);
$extension_ups = end($arr_upsfile);
if('csv' == $extension_ups){
    $reader_ups = new \PhpOffice\PhpSpreadsheet\Reader\Csv();

}elseif('xls' == $extension_ups){
    $reader_ups = new \PhpOffice\PhpSpreadsheet\Reader\Xls();

}else {
    $reader_ups = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
 
}
$spreadsheet_ups = $reader_ups->load($_FILES['upsfile']['tmp_name']);
$sheetData_ups = $spreadsheet_ups->getActiveSheet()->toArray();

$columns = $sheetData_ups[0];
$ups = [];
for ($i = 1; $i < count($sheetData_ups); $i++) {
    $row = $sheetData_ups[$i];
    $ups[$i] = array_combine($columns, $row);
}

var_dump($ups);

This will first get the columns names from the first row of the spreadsheet. Then, it will create an empty associative array called ups. For each row in the spreadsheet, the code will create a new key-value pair in the ups array, where the key is the column name and the value is the value in the row.

Melih Sevim
  • 930
  • 6
  • 9
  • many thanks. you saved my day! – Mehmet Aug 04 '23 at 17:51
  • This works fine for me but I need some more help. I have almost 158 columns in excel sheet and there are columns named Description which is repeating many times, like on column index 13, column index 24 , column index 54 etc... I want to pull the data from index 13.. can we do that? @Melih Sevim – Alex Aug 17 '23 at 09:09