我有一个自定义数据库表,用于存储ID,CATEGORY,MAKE和MODEL。
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;
?>
这将输出如下内容:
重型卡车
字体修改
M2自动修车机
VOLVO AUTOHAULER
工具车
保时捷
保时捷904
ROSSION
Q1R
第一季度
我可以用正确的类别下的品牌和正确的品牌下的型号列出所有产品。但是,我希望它们以不同的方式布置。我希望能够将制造商和模型包装在3列布局中,并且将模型隐藏在每个制造商之下,直到单击为止。
但是,当我尝试将它们包装在浮动列div中时,所有这些当然都会在foreach循环中弄乱了。我需要一种更好的查询和输出数据的方法。
以下是我希望它获得的示例代码:
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>
答案 0 :(得分:0)
很抱歉迟到了答案。
这是一个优雅的解决方案。诀窍是以“分组”方式将初始获取的数据($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
中,我添加了两个新记录,以便测试每个make
是否显示四个以上category
。搜索“ @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', '')
;