I am trying to develop a script where people can import items to my site. One field in the import file is "category", which has an example form such as:

Consumer Electronics:Televisions:Samsung

I then put this into an array where the colon is the separator here:
$categoryarray = explode(":",$category);
$level1 = $categoryarray[0];
$level2 = $categoryarray[1];
$level3 = $categoryarray[2];

Everything is good up until here. Next, I need to get the products in the import file in sync with my store categories in the database. My database has a table called categories:

id | level1 | level 2 | level 3 | level4 | level5
int | vchar | vchar | vchar | vchar | vchar

What I need to do is match the imported category levels with the ones in my database and return the category id number. I would like to match level 1 in the database first. If found, then find any level2 within level1 in the category tree, and so on. If a category is not found, such as level4, then stick with the first 3 found and grab the available id.

Is there any efficient way to do this? Also, this would need to be a quick script that could handle thousands of items during an import.