PHP Trouble renaming array key
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();
The array is returned before and after as this:
LeadID
AddDat开发者_如何学Ce LastName FirstName Address City State ZipCode LeadLocator Phone Email Sex Comments
At the end, I still get EveningPhone not defined errors from a file that uses Phone as the phone number..
Anybody have any ideas?
You need to use
if (!in_array('EveningPhone', $headers)) {
because the $headers
array is a normal indexed list after you just read it via fgetcsv
. Therefore array_key_exists won't work. You might later use it as dict, but at this point it isn't yet an array key.
To replace the entry use:
$headers[array_search("EveningPhone", $headers)] = "Phone";
fgetcsv does not return an associative array. It will return an array with the data as values so you should be using in_array or array_search (when you need the key). The code that reads the actual data is probably using array_combine to build an associative array using the header.
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 (!in_array('EveningPhone', $headers)) {
if ($phoneKey = array_search('Phone', $headers)) {
$headers[$phoneKey] = 'EveningPhone';
} else {
die("other");
}
}
format::neat_r($headers); // basically print_r but adds a new line to read it easier...
die();
精彩评论