guyfromfl Posted April 22, 2011 Share Posted April 22, 2011 I am reading hundreds of CSVs to import into a DB. Some of the column names contain the same data but have different names across all the files. For example, one file will say Phone where the other says EveningPhone...both contain the same data, different names. I am trying to rename everything to EveningPhone because I had most of the code done when i realized there were different header names in different files. Too lazy to replace all i guess.. I am creating an assoc array to match the data then off to the db it goes.. The problem is I cannot get the keys to rename to one convention. Here is the function where it happens: public function readCSV($file) { /** * @todo: LOAD THE FILE INTO A MULTIDIMENSIONAL ASSOCIATIVE ARRAY TO DETERMINE THE FILEDS */ // Read the first line to get the headers $headers = fgetcsv($file); if (!array_key_exists('EveningPhone', $headers)) { if (array_key_exists('Phone', $headers)) { $headers['EveningPhone'] = $headers['Phone']; unset($headers['Phone']); } else { die("other"); } } format::neat_r($headers); // basically print_r but adds a new line to read it easier... die(); At the end, I still get EveningPhone not defined errors from a file that uses Phone as the phone number.. Anybody have any ideas? Link to comment https://forums.phpfreaks.com/topic/234460-renaming-array-key-not-working/ Share on other sites More sharing options...
sunfighter Posted April 24, 2011 Share Posted April 24, 2011 You are using the wrong function "array_key_exists". Try this <?php $headers = fgetcsv($file); if(in_array('Phone',$headers)){ $key = array_search('Phone', $headers); $new = array($key => "EveningPhone"); $final = array_replace($headers, $new); } ?> Link to comment https://forums.phpfreaks.com/topic/234460-renaming-array-key-not-working/#findComment-1205586 Share on other sites More sharing options...
guyfromfl Posted May 17, 2011 Author Share Posted May 17, 2011 The problem was I was reading the data as it was in a different stage of me processing it...I dunno how to describe it but sunfighter was right. Link to comment https://forums.phpfreaks.com/topic/234460-renaming-array-key-not-working/#findComment-1216645 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.