I am having trouble with writing a simple(!) PHP function to return an array of values under the following scenario.
I have a database table that simply lists parent and child categories (e.g. menu, sub menu, sub sub menu) in two fields ‘parent_id’ and ‘category_id’. I want to tunnel down through the table to pull out all the bottom category_ids – i.e. those that are not listed as ‘parents’ to any others but are children (or grand children or great grand children) of the category_id input to the function
I have a function a bit like this (it runs on osCommerce based code so the sql query stuff looks odd
function tep_get_bottom_categories( $categories_id) {
$bottom_categories_query = tep_db_query("select categories_id from categories where parent_id = '" . $categories_id . "'");
while ($bottom_categories = tep_db_fetch_array($bottom_categories_query)) {
if(XXXXXXXXXXXXX)//<---- tried lots of stuff here
{$results[]=$bottom_categories['categories_id'];}
else
{tep_get_bottom_categories( $bottom_categories['categories_id']);
}
}//end while loop
}// end function
If I input a value to the function that has children then it will produce those in an array of $bottom_categories and then do the same all the way down to the final bottom categories – however these are not singled out and placed in the $results array as I need something to go where XXXXXXXXXXXXXX is but that is evading me mightily.
I’m assuming that I need to label each loop of the function in some way but I fail to see how – thanks – Graeme
2
Answers
I would always run the else case and check if the query has any results. If it has no children you are ready and insert it into the list; otherwise same as before.
Example code:
You can do this purely in SQL: