CSV to Associative Array

前端 未结 6 1424
孤城傲影
孤城傲影 2020-11-28 05:58

I\'ve seen numerous examples on how to take a CSV file and then create an associative array with the headers as the keys.

For example:

Brand,Model,Pa         


        
6条回答
  •  星月不相逢
    2020-11-28 06:30

    Try this simple algorithm:

            $assocData = array();
    
            if( ($handle = fopen( $importedCSVFile, "r")) !== FALSE) {
                $rowCounter = 0;
                while (($rowData = fgetcsv($handle, 0, ",")) !== FALSE) {
                    if( 0 === $rowCounter) {
                        $headerRecord = $rowData;
                    } else {
                        foreach( $rowData as $key => $value) {
                            $assocData[ $rowCounter - 1][ $headerRecord[ $key] ] = $value;  
                        }
                    }
                    $rowCounter++;
                }
                fclose($handle);
            }
    
            var_dump( $assocData);
    

提交回复
热议问题