回显多个字段属于一个字段,而不多次打印一个字段php

问题描述 投票:0回答:1

我只有几个字段与一个字段匹配。对于示例,我将字段大小作为属性,但是它具有许多与其匹配的字段。我想回声类似:尺寸: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 mysql sql echo
1个回答
0
投票

如果我正确地遵循了您的说明,则可以使用(正确)聚合和GROUP_CONCAT()

SELECT 
    categories.title AS title_categories , 
    attributes.title AS title_attributes,  
    GROUP_CONCAT(labels_atr.title) AS title_labels_atrs
FROM categories
INNER JOIN attributes ON attributes.id=categories.id
INNER JOIN labels_atr ON labels_atr.id_atr=categories.id
GROUP BY categories.title, labels_atr.title
© www.soinside.com 2019 - 2024. All rights reserved.