I have a shopping cart im making. And I'm stumped at finding out how I can load products within multi-level categories that are children of the category im looking at.
For example: -Cars Subarus (Legacy, Outback) - Holden (Commodore, Calais) - Toyota (Corolla, Camry)
If i'm looking in the cars category, i can select the child category but I cant view the actual products that are in those sub-categories. Is there any way I can do this? even if you can have unlimited levels of categories like "ROOT > Cars > Sedan > Subaru's..."?
Each product has a category ID which it relates to a category. Each category has its unique ID and a 'parent' id which has the ID of the category that it's a child of.
I think what you'll need to do is build up a list of category IDs to then construct an IN
clause for your sql. Let's say you have the following category structure:
To get all descendants of a category, you'll need to loop through the parent/child structure with something like this:
/**
* I'm only writing pseudocode here btw; I haven't tested it.
* Obviously you'll need to fire the SQL commands...
*/
function getKids ($id, $found = array())
{
array_push ($found, $id);
$nbrKids = "select count(id) from category where parent_id = $id";
if ($nbrKids > 0) {
$newKids = "select id from category where parent_id = $id";
foreach ($newKids as $kid) {
return getKids ($kid, $found);
}
}
else {
return $found;
}
}
Then call getKids()
like this, where $id
is your category id:
$ids = getKids($id);
$ids
is an array of all the categories you are interested in. You could then use join()
to construct an SQL string:
$sql = "select * from cars where category_id in (" . join (",", $ids) . ")";
For correctness, you should check that $ids
has at least 1 member first, otherwise your SQL query will be invalid.
[edit: actually in the above code, $ids
will always have at least one member: the initial id. However, the code doesn't verify the initial id is a valid category_id. ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.