Jump to content

Renaming array key not working.


guyfromfl

Recommended Posts

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
Share on other sites

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
Share on other sites

  • 4 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.