这个想法是,在每个主要类别的菜单中,如果有产品,则显示其中包含的第一个产品的图像。如果产品存在,则显示,但如果在下一次迭代中,产品的下一个主要类别不存在,则显示上一个的图像,并且应该有一个存根。告诉我,有什么问题?
//определение категорий
$sql = "SELECT name,id FROM category WHERE parrent =''";
if($result = $conn->query($sql)){
foreach($result as $row){
echo "<div class=\"uk-card uk-flex uk-flex-center uk-flex-middle\">";
echo "<div class=\"menu_items\"><div>";
$menu_category_name = $row["name"];
$menu_category_id = $row["id"];
//определение картинки главной категории
$sql = "SELECT id FROM products WHERE category='$menu_category_id' LIMIT 1";
if($result = $conn->query($sql)){
foreach($result as $row){
$firstproduct_id = $row["id"];
if ($firstproduct_id != '') {
$sql = "SELECT image FROM images WHERE product_id ='$firstproduct_id' LIMIT 1";
if($result = $conn->query($sql)){
foreach($result as $row){
$categoryimage = $row["image"];
}} else { echo "Ошибка: " . $conn->error;}
} else {
$categoryimage = "../ui/img/noimage.jpg";
}
}} else { echo "Ошибка: " . $conn->error;}
echo "<ul class=\"uk-nav-default\" uk-nav style=\"padding-left:14px;\"><li><a href=\"category.php?id=$menu_category_id\"><b>$menu_category_name</b></a></li></ul>";
//определение максимального количества субкатегорий
$sql = "SELECT name,id FROM category WHERE parrent ='$menu_category_id'";
if($result = $conn->query($sql)){
$rowsCount = $result->num_rows; // количество полученных строк
}
//определение субкатегорий
$sql = "SELECT name,id FROM category WHERE parrent ='$menu_category_id' LIMIT 4";
if($result = $conn->query($sql)){
foreach($result as $row){
$menu_category_name_sub = $row["name"];
$menu_category_id_sub = $row["id"];
echo "<ul class=\"uk-nav-sub\"><li><a href=\"category.php?id=$menu_category_id_sub\"> - $menu_category_name_sub</a></li></ul>";
} } else { echo "Ошибка: " . $conn->error;}
if ($rowsCount>=5){
echo "<ul class=\"uk-nav-sub\"><li><a href=\"category.php?id=$menu_category_id\"> - Смотреть все</a></li></ul>";
}
echo "</div><div><img style=\"max-width:150px; object-fit: cover;\" src=\"$categoryimage\"></div></div>";
echo "</div>";
} } else { echo "Ошибка: " . $conn->error;}
如果结果为空,则不会进入循环。对结果的行数执行 if
或者,在我看来,您可以像这样简化代码