So I have a table in a database filled with categories structured like this:
pk int: cat_id
int: parent_id
varchar: cat_name
A top level category has a null parent_id and there could be several levels of children. Basically, I am taking a search string and matching it against the category names, and if the category has parents then I want to display the full path in breadcrumb fashion for all matches. Here is pseudo code for what I am doing now:
search_string = whatever;
result = query db and find all category names matching "%whatever%";
foreach(result)
{
parent_id = result[parent_id];
result_path = result[cat_name];
while(parent_id != null)
{
result2 = query db and find cat_id = parent_id;
result_path = result2[cat_name] + " > " + result[path];
parent_id = result2[parent_id];
}
print result_path;
}
Is there a more efficient way to do this other than the nested loop and database queries?
Thanks for any input.