Page 1 of 1

help deleting an empty array from a multidimensional array

Posted: Sat May 30, 2009 10:40 pm
by sigkill-9
Hi, I'm fairly new to PHP, am in an advanced PHP class in college now and I'm working on a project that requires me to import a comma separated list of users (first name, last name, email address) into a mysql db but I'm having an issue with the import and would like some help.

I have the import function working, E.G it does import the users into the db, however, when my function gets to the end of the CSV file it adds an empty array and, of course, gives me a mysql error because of the null entries of the last array.

I'm trying to figure out how to select and erase empty arrays from the multidimentional array $lineItem2, and have been working on it all day, but the solution eludes me.

First, here is what the array looks like after its imported and processed:
(note the empty array at bottom)

Code: Select all

Array(
    [0] => Array(
            [fname] => Todd
            [lname] => Preston
            [email] => tpreston@somewhere.com)
 
    [1] => Array(
            [fname] => Sam
            [lname] => Phillips
            [email] => sphillips@somewhere.net)
 
    [2] => Array(
            [fname] => 
            [lname] => 
            [email] => )
)
Below is the code i've come up with for searching through the array to find empty arrays, but my method to delete the empty key isnt working. I'm sure its a quick fix for someone out there, but I'm sort of a PHP noob... still learning... and not very good with arrays :roll: :
$lineItem2 is the multidimensional array that contains all the user info.

Code: Select all

 
    foreach($lineItem2 as $key => $value){
        //fname is the first value in each array, if it's empty, drop it.
        if($value['fname'] === ''){ 
           unset($key); //not working
        }
 
        //set values for db insertion
        $fname = $value['fname'];
        $lname = $value['lname'];
        $email = $value['email'];
 
        //insert new array values into db
        $userAdmin->import_users($fname,$lname,$email);
 
    }


I'm sure there are a lot of other, more desirable/efficient ways to do this, but like I said I'm still new to PHP and still learning...
Any help would be greatly appreciated, thanks!

Re: help deleting an empty array from a multidimensional array

Posted: Sun May 31, 2009 12:00 am
by requinix
Wouldn't it be easier to make sure the empty array never shows up in the first place?

What code are you using to read from the file into the array?

Re: help deleting an empty array from a multidimensional array

Posted: Sun May 31, 2009 1:37 am
by sigkill-9
Well, I'm not sure, thats why I'm here :)

I'm not familiar with importing files to db's, this is my first attempt.
Here's the entire code I'm using to read from the file into the array:

Code: Select all

 
require 'import.php'; //db model, contains user_import function
 
$import = new userAdmin;
 
if (isset($_FILES['uploadedfile'])) {
    $inFile = fopen($_FILES['uploadedfile']['tmp_name'], "r");
    $myData = fread($inFile, filesize($_FILES['uploadedfile']['tmp_name']));
    fclose ($inFile);
    $myDB = split("\n", $myData);
 
    //split each line by comma values
    foreach($myDB as $data){
        $lineItem[] = split(",", $data);
    }
 
    //create array for db import
    foreach($lineItem as $key){
        $lineItem2[] = array('fname' => $key[0],
                                     'lname' => $key[1],
                                     'email' => $key[2]);
    }
 
    //remove empty arrays from $lineItem2
    foreach($lineItem2 as $key => $value){
         //fname is the first value in each array, if it's empty, drop it.
         if($value['fname'] === ''){
            unset($key); //not working
         }
  
         //set values for db insertion
         $fname = $value['fname'];
         $lname = $value['lname'];
         $email = $value['email'];
  
         //insert new array values into db
         $import->import_users($fname,$lname,$email);
    }
}

Re: help deleting an empty array from a multidimensional array

Posted: Sun May 31, 2009 3:13 am
by requinix
The problem with how you're using unset is that it works directly on variables. If you say unset($variable) then $variable will disappear. It doesn't know about how $variable was an array key, and it certainly won't assume you meant to unset that entry in the array.

But first, the simpler solution to everything. Rather than try to parse the file yourself, let PHP do it for you. Then there's no need for multiple arrays and more confusing code.

Code: Select all

require 'import.php'; //db model, contains user_import function
 
$import = new userAdmin;
 
if (isset($_FILES['uploadedfile'])) {
    $inFile = fopen($_FILES['uploadedfile']['tmp_name'], "r");
    while ($line = fgetcsv($inFile)) {
        // if the line (or first name) is empty then continue on with the next line in the file
        if (trim($line[0]) == "") continue;
        // if $line doesn't have three items in it (first name, last name, email) continue
        if (count($line) != 3) continue;
 
        // the first name is $line[0], last name is $line[1], and email is $line[2]
        $import->import_users($line[0], $line[1], $line[2]);
    }
    fclose ($inFile);
}
Your original code tried to break the entire process down into individual steps.
1. Read file
2. Split file into lines
3. Split lines into parts
4. Decide which parts are which
5. Import

That's good. You needed a loop, but you tried to put every step there into its own loop.
1. Read file
2. Split file into lines
3. For each line in the file
3.1. Split into parts
4. For each set of parts
4.1. Separate into first name, last name, and email
5. For each first name, last name, and email
5.1. Import

See how there's a lot of repetition in there? You keep using a "for each" at every step. Why not
3. For each line in the file
3.1 Split into parts
3.2 Separate into first name, last name, and email
3.3 Import

Good, but step 3.2 isn't really necessary - we already know which part corresponds to what data. So that step is redundant. Adding fgetcsv just makes step 3.1 (which now includes 3.2) easier.

Re: help deleting an empty array from a multidimensional array

Posted: Sun May 31, 2009 3:44 am
by sigkill-9
Thank you for your insight and your help, it is working great now.

Next on the list, figuring out how to check the imported csv file against the database to prevent mysql errors for duplicate entries. Do you have any suggestions?

Re: help deleting an empty array from a multidimensional array

Posted: Sun May 31, 2009 4:39 am
by requinix
If you have your primary key/unique keys set up correctly, just do a normal INSERT (or better yet, an INSERT IGNORE). MySQL will check for existing rows for you and won't do the insert if any are found.

Re: help deleting an empty array from a multidimensional array

Posted: Sun May 31, 2009 6:47 am
by Darhazer
You can use array_filter with callback function to remove the empty elements from the array.

Re: help deleting an empty array from a multidimensional array

Posted: Sun May 31, 2009 3:44 pm
by sigkill-9
tasairis wrote:If you have your primary key/unique keys set up correctly, just do a normal INSERT (or better yet, an INSERT IGNORE). MySQL will check for existing rows for you and won't do the insert if any are found.
Thats good advice, and I'll definately use that technique. My goal now is, once the user initiates the file upload, to have php look into the file and compare its contents with the contents in the users table in the db and if it finds entries in the csv file that already exist in the db, let the user know about it.

I dont have the time rite this second to write the code, i'll work on it in a few hours, but was hoping in the meantime someone could provide some feedback/code examples that would help perform this db/csv compare function.