Search code examples
phparraysexcelcodeigniter

Combined two arrays and the result returned has an empty key and value


I have an excel sheet which is read and converted to an array. Here is the code :

    $filename = $_FILES['importProjects']['tmp_name'];
    $objPHPExcel = PHPExcel_IOFactory::load($filename);

        $i = 0;
        $all_sheet = $objPHPExcel->getSheetCount(); //total number of sheets
        $arrayInsertProject =   array();
        $arrayUpdateProject =   array();
        while ($i < $all_sheet){
            $objPHPExcel->setActiveSheetIndex($i); 
            $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
            $arrayCount = count($allDataInSheet);  // Here get total count of rows from the sheet
            $column = 'A';
            $project_cnt=1;
            $dataIns = array();
            for ($row = 1; $row <= $arrayCount; $row++) { //loop through rows
                if($row ==1){
                    $highestColumn = $objPHPExcel->getActiveSheet()->getHighestColumn();
                    $rowDataHeader = $objPHPExcel->getActiveSheet()->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                    NULL,
                    TRUE,
                    FALSE);
                    $rowDataHeader  =   array_reduce($rowDataHeader, 'array_merge', array());       
                }else {
                    $highestColumn = $objPHPExcel->getActiveSheet()->getHighestColumn();

                    $rowData = $objPHPExcel->getActiveSheet()->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                    NULL,
                    TRUE,
                    FALSE);
                   $dataIns =    array_combine($rowDataHeader, $rowData);
                }
            }
        }

When I print this array $dataIns, I get something like this :

Array
(
     [intProjectSlNo] => 1069
     [chvProjectNameEng] => New
     [slug] => this-is -test
     [nchvSecType] => 1754349
     [] => 
)

How to remove the empty key => value pair ?


Solution

  • Add this after while loop of your code

    foreach($dataIns as $key=>$value)
    {
        if(is_null($value) || $value == '')
            unset($dataIns[$key]);
    }
    
    print_r($dataIns);