phpphpspreadsheet

Convert PHP Spreadsheet generated Multidimensional Array to Associative Array using first row as columns names(key)


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

Solution

  • 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.