我的数据库类别和产品是:
Category Table
:id,name,parent_id
Product Table
:id,name,category_id
我的分类菜单是:
-Category A
--Category A1
--Category A2
---Category A2a etc..
每个产品只有一个相关的类别:
Product1 -> Category A1
Product2 -> Category A2
Product3 -> Category A2a etc..
所有产品类别和子类别的代码
category.php?category_id=1 (exp. category A)
<?php
function FetchAllRows($sql) {
global $db;
$stmt=$db->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}
function getCategoryChild($children) {
$sql = "SELECT * FROM `category` WHERE `parent_id` = $children";
$rows = FetchAllRows($sql);
$sub_category_id = array();
foreach($rows as $row) {
// $sub_category_id[$row['id']] = getCategoryChild($row['id']);
$cat = getCategoryChild($row['id']);
$sub_category_id[] = array(
'children' => $cat,
'category_id' => $row['id']
);
}
return $sub_category_id;
}
$a = getCategoryChild($category_id);
echo $in = join(',', array_fill(0, count($a), '?'));
$query="SELECT * FROM product WHERE category_id IN ($in)";
我尝试了这个最新的应用程序。我们没有得到结果。我英文不太好。希望存在。直到我想要将数组元素转移到SQL中。
答案 0 :(得分:0)
我解决了这个问题。
我删除了这两行。
echo $in = join(',', array_fill(0, count($a), '?'));
$query="SELECT * FROM product WHERE category_id IN ($in)";
我只投资了category_id&#39>。
foreach($a as $index => $b) {
$subs[$index] = $b['category_id'];
}
$ids = implode($subs,',');
$query = $db->query("SELECT * FROM `product` WHERE category_id IN($ids);");