【问题标题】:echo multiple fields belong to one field, without printing the one field many times php [duplicate]回显多个字段属于一个字段,而不多次打印一个字段php [重复]
【发布时间】:2020-06-07 23:58:32
【问题描述】:

我有几个字段匹配一个字段。例如,我将字段大小作为属性,但它有许多与之匹配的字段。 我想回应类似的东西: 尺寸: s、m、l、xl、xxl…… 但是当我打印它时,它就像: 尺寸: s 尺寸:米 尺寸:l 尺寸:xl..

如何正确打印? 代码:

<?php

// Create connection
$conn = new mysqli('localhost', 'root','','catalog');
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT DISTINCT categories.title AS title_categories , attributes.title AS title_attributes,  labels_atr.title AS title_labels_atr
FROM categories
INNER JOIN attributes ON attributes.id=categories.id
INNER JOIN labels_atr ON labels_atr.id_atr=categories.id
GROUP BY labels_atr.title
";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       extract($row);
        echo "category: ".$title_categories.",attributes: ".$title_attributes."<BR>";
        echo "labels_atr: ".$title_labels_atr."<BR>";
} 
}
else {
    echo "0 results";
}

$conn->close();
?>

输出:

category: Pants,attributes: Size
    labels_atr: 32X32
    category: Pants,attributes: Size
    labels_atr: 32X34
    category: Pants,attributes: Size
    labels_atr: 32X36
    category: Pants,attributes: Size
    labels_atr: 34X32
    category: Pants,attributes: Size
    labels_atr: 34X36
    category: Pants,attributes: Size
    labels_atr: 36X32
    category: Sale,attributes: Size
    labels_atr: L
    category: Sale,attributes: Size
    labels_atr: M
    category: Sale,attributes: Size
    labels_atr: S
    category: Sale,attributes: Size
    labels_atr: XL
    category: Sale,attributes: Size
    labels_atr: XS
    category: Sale,attributes: Size
    labels_atr: XXL
    category: Shirts,attributes: Color
    labels_atr: Black
    category: Shirts,attributes: Color
    labels_atr: Blue
    category: Shirts,attributes: Color
    labels_atr: Grey
    category: Shirts,attributes: Color
    labels_atr: Orange
    category: Shirts,attributes: Color
    labels_atr: Red
    category: Shirts,attributes: Color
    labels_atr: White
    category: Shirts,attributes: Color
    labels_atr: Yellow

【问题讨论】:

  • 您希望通过查询还是使用 PHP 来完成此操作?
  • 它不会对我嘀咕,只要结果会好,我可以做一个html,这样例子的大小就是标题和s,m ,l 等。将是字段和标题
  • 在 10 多年的编程生涯中,我从未找到一个令人信服的理由在我的任何项目中使用 extract()。我建议不要在这里 - 没有真正的好处。

标签: php mysql sql group-by


【解决方案1】:

如果我正确地关注了你,你可以使用(正确的)聚合和GROUP_CONCAT()

SELECT 
    c.title AS title_categories , 
    a.title AS title_attributes,  
    GROUP_CONCAT(l.title) AS title_labels_atrs
FROM categories c
INNER JOIN attributes a ON a.id = c.id
INNER JOIN labels_atr l ON l.id_atr = c.id
GROUP BY c.title, a.title

【讨论】:

  • 它仍然会多次打印每个标题
  • 您应该使用 GMB 的建议并找出您的实施不起作用的原因。这是最合适的技术。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 2017-02-05
  • 1970-01-01
相关资源
最近更新 更多