Forums

Renaming keys

chriso0258 05 Nov, 2015
Hello,

I have a script that reads a csv file in the onLoad event. (My echo statement is merely so I can see that the file is read). Here is my code:
<?php
$personnel = array();
if (file_exists("/var/www/html/tmp/personnel.csv")) { 
	$file = fopen("/var/www/html/tmp/personnel.csv","r");
}else {
	echo "<h2>The file does NOT exist</h2>";
}

while(!feof($file)) {
$personnel = fgetcsv($file);
if (!empty($personnel)){
array_push($form->data, $personnel);
	foreach($form->data as $key) {
		if ($key != NULL) {
			foreach($key as $value) {
				if ($value != NULL) {
					echo $value . " ";
				}
			}
		}
	}	
}
echo "<br><br>";
} // End while(! feof($file))	
fclose($file);
?> 

I have a data-to-session action in the onLoad and a session-to-data in the onSubmit event. Here is how the array looks:
Array
(
    [chronoform] => process_csv
    [event] => submit
    [button1] => Submit
    [0] => Array
        (
            [0] => Eighth
            [1] => The
            [2] => Henry
            [3] => staff
        )

    [1] => Array
        (
            [0] => Polo
            [1] => 
            [2] => Marco
            [3] => staff
        )

    [2] => Array
        (
            [0] => Phant
            [1] => E
            [2] => El
            [3] => staff
        )

    [3] => Array
        (
            [0] => Coon
            [1] => 
            [2] => Ray
            [3] => staff
        )

    [4] => Array
        (
            [0] => Berry
            [1] => Grape
            [2] => Dunns
            [3] => staff
        )
)

Array [0] will be the column lname (last name).
Array [1] will be the column fname (first name)
Array [2] will be the column mname (middle name)
Array [3] will be the column classification

How can I adjust my initial script (or add another script) to rename the keys 0, 1, 2, 3 to the appropriate column names so I can import them into the db using a db Save action.

Thanks for your help.
Chris
GreyHead 05 Nov, 2015
Hi Chris,

Please try this[code// . . .
$personnel = fgetcsv($file);

if ( empty($personnel) ) {
return;
}
$keys = array (
'lname',
'fname',
'mname',
'classification'
);
$temp = array();
foreach ( $personnel as $p ) {
$temp[] = array_combine($keys, $p);
}
$form->data['personnel'] = $temp;
?>[/code]
I think that you can avoid using sessions by having this code in the On Submit event of the form.

Bob
This topic is locked and no more replies can be posted.