html - 车辆类别、品牌和型号查询

标签 html css

我有一个自定义数据库表,我在其中存储 ID、类别、品牌和型号。

id    category       make                   model
---   --------      ------                  -------
1     heavy truck   fontaine modification   m2 autohauler
2     heavy truck   fontaine modification   volvo autohauler
3     kit car       porsche                 porshe 904
4     kit car       rossion                 Q1
5     kit car       rossion                 Q1R

SQL 测试数据链接:https://sqltest.net/#246173

我正在使用以下查询数据库中的此表,并尝试从输出中删除重复的类别和品牌:

<?php
$query = $wpdb->get_results( "SELECT * FROM table_name");
$category = '';
$make = '';
foreach($query as $mm) :
    if($mm->category != $category):
         echo '<div class="clearfix"></div>';
         echo '<div class="category"><strong>'.$mm->category.'</strong></div>';
        $category = $mm->category;
    endif;

    if($mm->make != $make):
        echo '<div class="make '.$mm->make.'">'.$mm->make.'</div>';
        $make = $mm->make;
    endif;
    if($mm->model):
        echo '<div class="model">'.$mm->model.'</div>';
    endif;

endforeach;
?>

这将输出如下内容:

重型卡车

FONTAINE 修改

M2 自动搬运车

沃尔沃汽车卡车

套件车

保时捷

保时捷 904

ROSSION

Q1R

第一季度

我可以在正确的类别下列出所有品牌,在正确的品牌下列出型号。但是,我想让它们以不同的方式布置。我希望能够将品牌和型号包装在 3 列布局中,并在单击之前隐藏每个品牌下的型号。

但是,当我尝试将它们包装在一个 float 列 div 中时,它当然会在 foreach 循环中搞砸了。我需要一种更好的方法来查询和输出这些数据。

这是它目前的样子: enter image description here

这是我想要达到的目标的屏幕截图: enter image description here

这是我希望它达到的示例代码:

jQuery(document).ready(function($){
	$(".make").click(function() {
	  $(this).next('.model').toggle();
	});
});
.make-model:after {
	clear: both;
	content: "";
	display: table;
}
.make-model .category {
	background: #68bac9;
	color:#FFF;
	font-weight: 600;
	padding-left: 7px;
	margin-bottom: 7px;
}
.make-model .make {
	color: #026e81;
	font-weight: 600;
	margin: 0;
	padding: 0;
	cursor: pointer;
}
.make-model .make:after {
	font-family: "FontAwesome";
	content: "\00a0\f0d7";
	color: #8ccdd9;
}
.make-model .model {
  list-style:none;
	color: #026e81;
	font-weight: 400;
	display: none;
  margin:0;
  padding:0;
}
.d-1of4 {
  float: left;
  padding-right: 0.75em;
  width: 25%;
}
.clearfix {
	clear:both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="make-model">
<div class="category">
	<strong>HEAVY TRUCK</strong>
</div>
<div class="d-1of4">
	<div class="make">FONTAINE MODIFICATION</div>
	<ul class="model">
		<li>M2 AUTOHAULER</li>
		<li>VOLVO AUTOHAULER</li>
	</ul>
</div>
<div class="clearfix"></div>
<div class="category">
	<strong>KIT CAR</strong>
</div>
<div class="d-1of4">
	<div class="make">PORSCHE</div>
	<ul class="model">
		<li>PORSCHE 904</li>
	</ul>
</div>
<div class="d-1of4">
	<div class="make">ROSSION</div>
	<ul class="model">
		<li>Q1</li>
		<li>Q1R</li>
	</ul>
</div>
<div class="d-1of4">
	<div class="make">S-1 ROADSTER</div>
	<ul class="model">
		<li>S-1 ROADSTER</li>
	</ul>
</div>
<div class="clearifx"></div>
</div>

最佳答案

抱歉回答迟了。

方法一:

这是优雅的解决方案。诀窍是将初始获取的数据 ($vehicles) 以“分组”方式复制到另一个数组 ($groupedVehicles) 中。然后将迭代此分组列表,并根据其结构构建 HTML 代码。

初始数据($vehicles):

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [category] => HEAVY TRUCK
            [make] => FONTAINE MODIFICATION
            [model] => M2 AUTOHAULER
            [part_number] => 
        )

    [1] => stdClass Object
        (
            [id] => 2
            [category] => HEAVY TRUCK
            [make] => FONTAINE MODIFICATION
            [model] => VOLVO AUTOHAULER
            [part_number] => 
        )

    [2] => stdClass Object
        (
            [id] => 11
            [category] => KIT CAR
            [make] => FERRARI
            [model] => 488 GTB
            [part_number] => 
        )

    [3] => stdClass Object
        (
            [id] => 12
            [category] => KIT CAR
            [make] => FERRARI
            [model] => 488 SPIDER
            [part_number] => 
        )

    [4] => stdClass Object
        (
            [id] => 3
            [category] => KIT CAR
            [make] => PORSCHE
            [model] => PORSCHE 904
            [part_number] => 
        )

    [5] => stdClass Object
        (
            [id] => 4
            [category] => KIT CAR
            [make] => ROSSION
            [model] => Q1
            [part_number] => 
        )

    [6] => stdClass Object
        (
            [id] => 5
            [category] => KIT CAR
            [make] => ROSSION
            [model] => Q1R
            [part_number] => 
        )

    [7] => stdClass Object
        (
            [id] => 6
            [category] => KIT CAR
            [make] => S-1 ROADSTER
            [model] => S-1 ROADSTER
            [part_number] => 
        )

    [8] => stdClass Object
        (
            [id] => 7
            [category] => KIT CAR
            [make] => STERLING SPORTS CARS
            [model] => CIMBRIA
            [part_number] => 
        )

    [9] => stdClass Object
        (
            [id] => 8
            [category] => KIT CAR
            [make] => STERLING SPORTS CARS
            [model] => FORTVAC
            [part_number] => 
        )

    [10] => stdClass Object
        (
            [id] => 9
            [category] => KIT CAR
            [make] => STERLING SPORTS CARS
            [model] => STERLING
            [part_number] => 
        )

    [11] => stdClass Object
        (
            [id] => 10
            [category] => KIT CAR
            [make] => STERLING SPORTS CARS
            [model] => VIPER 2000
            [part_number] => 
        )

)

分组数据($groupedVehicles):

Array
(
    [HEAVY TRUCK] => Array
        (
            [FONTAINE MODIFICATION] => Array
                (
                    [0] => M2 AUTOHAULER
                    [1] => VOLVO AUTOHAULER
                )

        )

    [KIT CAR] => Array
        (
            [FERRARI] => Array
                (
                    [0] => 488 GTB
                    [1] => 488 SPIDER
                )

            [PORSCHE] => Array
                (
                    [0] => PORSCHE 904
                )

            [ROSSION] => Array
                (
                    [0] => Q1
                    [1] => Q1R
                )

            [S-1 ROADSTER] => Array
                (
                    [0] => S-1 ROADSTER
                )

            [STERLING SPORTS CARS] => Array
                (
                    [0] => CIMBRIA
                    [1] => FORTVAC
                    [2] => STERLING
                    [3] => VIPER 2000
                )

        )

)

此解决方案的缺点是您必须复制整个数据列表。

这是我的文件。您可以按原样对其进行测试。我稍微改变了你的命名约定。虽然不是表结构。在表 wp_make_model 中,我添加了两条新记录,以测试每个 category 超过四个 make 的显示。搜索“@todo”并采取相应行动。我使用 PDO 扩展连接到数据库并为每个数据库记录构建一个对象。例如。模拟您的函数 get_results

vehicles.php:

<?php
require 'connection.php';

$sql = 'SELECT *
        FROM wp_make_model
        ORDER BY
            category ASC,
            make ASC,
            model ASC
        ';

$statement = $connection->prepare($sql);
$statement->execute();
$vehicles = $statement->fetchAll(PDO::FETCH_OBJ);

/*
 * Just for test-printing the data.
 * @todo Uncomment, see the results, delete.
 */
// echo '<pre>' . print_r($vehicles, TRUE) . '</pre>';
// Holds the list of vehicles grouped by category, make, model - in this order.
$groupedVehicles = [];

foreach ($vehicles as $vehicle) {
    if (!array_key_exists($vehicle->category, $groupedVehicles)) {
        $groupedVehicles[$vehicle->category] = [];
    }

    if (!array_key_exists($vehicle->make, $groupedVehicles[$vehicle->category])) {
        $groupedVehicles[$vehicle->category][$vehicle->make] = [];
    }

    $groupedVehicles[$vehicle->category][$vehicle->make][] = $vehicle->model;
}

/*
 * Just for test-printing the data.
 * @todo Uncomment, see the results, delete.
 */
// echo '<pre>' . print_r($groupedVehicles, TRUE) . '</pre>';
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo - Vehicles</title>

        <!-- CSS resources -->
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet">
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" rel="stylesheet" />
        <link href="vehicles.css" type="text/css" rel="stylesheet" />

        <!-- JS resources -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="vehicles.js" type="text/javascript"></script>
    </head>
    <body>

        <h1>
            Demo vehicles
        </h1>

        <div class="vehicles">
            <?php
            foreach ($groupedVehicles as $category => $makes) {
                $makesPerRow = 0;
                ?>
                <div class="category">
                    <?php echo $category; ?>
                </div>
                <?php
                foreach ($makes as $make => $models) {
                    $makesPerRow++;
                    ?>
                    <div class="d-1of4">
                        <div class="make">
                            <?php echo $make; ?>
                        </div>
                        <ul class="model">
                            <?php
                            foreach ($models as $model) {
                                ?>
                                <li>
                                    <?php echo $model; ?>
                                </li>
                                <?php
                            }
                            ?>
                        </ul>
                    </div>
                    <?php
                    if ($makesPerRow % 4 === 0) {
                        $makesPerRow = 0;
                        ?>
                        <div class="clearfix"></div>
                        <?php
                    }
                }

                if ($makesPerRow > 0) {
                    ?>
                    <div class="clearfix"></div>
                    <?php
                }
            }
            ?>
        </div>

    </body>
</html>

connection.php:

<?php

/*
 * This page contains the code for creating a PDO connection instance.
 */

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');
define('CHARSET', 'utf8');

// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */

// Create a PDO instance as db connection to db.
$connection = new PDO(
        sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
        , USERNAME
        , PASSWORD
        , [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => FALSE,
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
);

vehicles.js:

$(document).ready(function () {
    $(".make").click(function () {
        $(this).next('.model').toggle();
    });
});

vehicles.css:

/***************************************/
/* Base settings */
/***************************************/

html {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

*, *:before, *:after {
    -moz-box-sizing: inherit;
    -webkit-box-sizing: inherit;
    box-sizing: inherit;
}

html, body {
    margin: 0;
    padding: 10px;
    font-size: 100%;
    font-weight: 400;
    line-height: 1.8;
    color: #000;
    background-color: #fff;
}

body {
    font-size: 0.9375rem;
    position: relative;
}

h1 {
    text-transform: uppercase;
}

/***************************************/
/* Fonts */
/***************************************/

html, body {
    font-family: "Open Sans", Verdana, Arial, sans-serif !important;
}

h1, h2, h3, h4, h5, h6 {
    font-family: "Roboto Condensed", Verdana, Arial, sans-serif !important;
}

/***************************************/
/* Layout settings */
/***************************************/

.vehicles:after {
    clear: both;
    content: "";
    display: table;
}
.vehicles .category {
    background: #68bac9;
    color:#FFF;
    font-weight: 600;
    padding-left: 7px;
    margin-bottom: 7px;
}
.vehicles .make {
    color: #026e81;
    font-weight: 600;
    margin: 0;
    padding: 0;
    cursor: pointer;
}
.vehicles .make:after {
    font-family: "FontAwesome";
    content: "\00a0\f0d7";
    color: #8ccdd9;
}
.vehicles .model {
    list-style:none;
    color: #026e81;
    font-weight: 400;
    display: none;
    margin:0;
    padding:0;
}
.d-1of4 {
    float: left;
    padding-right: 0.75em;
    width: 25%;
}
.clearfix {
    clear:both;
}

方法二:

它的优点是不需要复制初始数据。虽然很难理解,但它确实需要对数据进行正确排序。对于此方法,只有 vehicles2.php 是相关的。其余文件相同。

vehicles2.php

<?php
require 'connection.php';

$sql = 'SELECT *
        FROM wp_make_model
        ORDER BY
            category ASC,
            make ASC,
            model ASC
        ';

$statement = $connection->prepare($sql);
$statement->execute();
$query = $statement->fetchAll(PDO::FETCH_OBJ);

/*
 * Just for test-printing the data.
 * @todo Uncomment, see the results, delete.
 */
// echo '<pre>' . print_r($vehicles, TRUE) . '</pre>';
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo - Vehicles</title>

        <!-- CSS resources -->
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet">
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" rel="stylesheet" />
        <link href="vehicles.css" type="text/css" rel="stylesheet" />

        <!-- JS resources -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="vehicles.js" type="text/javascript"></script>
    </head>
    <body>

        <h1>
            Demo vehicles
        </h1>

        <div class="vehicles">
            <?php
            $category = '';
            $make = '';
            $result = '';

            foreach ($query as $mm) {
                if ($mm->category !== $category) { // Current category is different than the previous one.
                    // End of previous category row (if any).
                    if ($category !== '') {
                        // Close the previous make container.
                        $result .= '</ul>';
                        $result .= '</div>';

                        // Clearfix if not already done after the last make container in previous category.
                        if ($makesPerRow > 0) {
                            $result .= '<div class="clearfix"></div>';
                        }
                    }

                    // Initialize for the current, newly created category.
                    $makesPerRow = 0;

                    // Define current category container.
                    $result .= '<div class="category">' . $mm->category . '</div>';
                    $category = $mm->category;

                    $makesPerRow++;

                    // Define the container of the first make.
                    $result .= '<div class="d-1of4">';
                    $result .= '<div class="make">' . $mm->make . '</div>';
                    $result .= '<ul class="model">';
                    $make = $mm->make;
                } else { // Current category is the same with the previous one.
                    if ($mm->make !== $make) { // The current make is different than the previous one.
                        // So, close the previous make container.
                        $result .= '</ul>';
                        $result .= '</div>';

                        // Clearfix if the 4th (or 8th, etc) make container was just closed.
                        if ($makesPerRow % 4 === 0) {
                            $makesPerRow = 0;
                            $result .= '<div class="clearfix"></div>';
                        }

                        $makesPerRow++;

                        // Define the container of the current make.
                        $result .= '<div class="d-1of4">';
                        $result .= '<div class="make">' . $mm->make . '</div>';
                        $result .= '<ul class="model">';
                        $make = $mm->make;
                    }
                }

                // Always executed in each iteration step.
                if ($mm->model) {
                    $result .= '<li>' . $mm->model . '</li>';
                }
            }

            echo $result;
            ?>
        </div>

    </body>
</html>

创建并填充数据库表:

CREATE TABLE `wp_make_model` (
  `id` int(20) unsigned NOT NULL AUTO_INCREMENT,
  `category` varchar(200) NOT NULL,
  `make` varchar(200) NOT NULL,
  `model` varchar(200) NOT NULL,
  `part_number` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

INSERT INTO `wp_make_model` (`category`, `make`, `model`, `part_number`)
VALUES
    ('HEAVY TRUCK', 'FONTAINE MODIFICATION', 'M2 AUTOHAULER', ''),
    ('HEAVY TRUCK', 'FONTAINE MODIFICATION', 'VOLVO AUTOHAULER', ''),
    ('KIT CAR', 'PORSCHE', 'PORSCHE 904', ''),
    ('KIT CAR', 'ROSSION', 'Q1', ''),
    ('KIT CAR', 'ROSSION', 'Q1R', ''),
    ('KIT CAR', 'S-1 ROADSTER', 'S-1 ROADSTER', ''),
    ('KIT CAR', 'STERLING SPORTS CARS', 'CIMBRIA', ''),
    ('KIT CAR', 'STERLING SPORTS CARS', 'FORTVAC', ''),
    ('KIT CAR', 'STERLING SPORTS CARS', 'STERLING', ''),
    ('KIT CAR', 'STERLING SPORTS CARS', 'VIPER 2000', ''),
    ('KIT CAR', 'FERRARI', '488 GTB', ''),
    ('KIT CAR', 'FERRARI', '488 SPIDER', '')
;

关于html - 车辆类别、品牌和型号查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978707/

相关文章:

javascript - 如果单击特定链接,如何更新 div 内容

css - 单击链接后我的悬停已停用

html - 在 Bootstrap 4 面包屑中右对齐文本

css - 当用作背景图像时,我的 SVG 图像忽略了它的样式表

javascript - 访问 :before pseudo selector 上的样式属性 "content"

jQuery - 当一张卡片悬停或有焦点时,模糊另一张

html - css hover 上的负边距导致抖动

javascript - Snap.svg 缩放和动画 SVG

css - 边界底部到 li,跨度不起作用

html - 选择 float 时损坏的元素