简体   繁体   中英

PHP Show Products within the child categories… custom shopping cart

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:

  • Cars (id:1)
    • Toyota (id:2, parent:1)
      • Mini (id:3, parent:2)
      • Corolla (id:4, parent:3)
    • Holden (id:5, parent:1)
      • Sports (id:6, parent:5)
      • HSV (id:7, parent:6)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM