gpt4 book ai didi

PHP MySQL 显示按公共(public)字段分组的多行

转载 作者:行者123 更新时间:2023-11-29 04:29:59 26 4
gpt4 key购买 nike

我想弄清楚如何列出 COMPANY 的 CATEGORY 和 BRAND ,其中的布局看起来类似于:

公司 1

  • 第 1 类:
    X 品牌
    Y品牌
    品牌Z

  • 第 2 类
    品牌A
    品牌B
    品牌 C

  • 类别 3
    品牌A
    品牌 X

我对 PHP + MySQL 不够熟悉,无法找到正确的 SEARCH 和 PHP 输出来实现此目的。

我的表看起来类似于:

COMPANY   | CATEGORY   | BRAND    --------------------------------Company 1 | Category 2 | Brand A  Company 1 | Category 2 | Brand B  Company 1 | Category 2 | Brand C  Company 1 | Category 1 | Brand X  Company 1 | Category 1 | Brand Y  Company 1 | Category 1 | Brand Z  Company 1 | Category 3 | Brand A  Company 1 | Category 3 | Brand X  

最佳答案

<?php
$result = mysql_query("
SELECT
*
FROM
some_table
ORDER BY
company,
category,
brand
")
or trigger_error('Query failed in '. __FILE__ .
' on line '. __LINE__ .'. '. mysql_error(), E_USER_ERROR);
if (mysql_num_rows($result)) {
$companies = array();
while ($row = mysql_fetch_assoc($result)) {
$companies[$row['company']][$row['category']][] = $row['brand'];
}

foreach ($companies AS $company => $categories) {
echo '<h2>'. htmlentities($company, ENT_COMPAT, 'UTF-8') .'</h2>';
echo '<ul>';
foreach ($categories AS $category => $brands) {
echo '<li>'. htmlentities($category, ENT_COMPAT, 'UTF-8');
foreach ($brands AS $brand) {
echo '<br><em>'. htmlentities($brand, ENT_COMPAT, 'UTF-8') .'</em>';
}
echo '<br>&nbsp;</li>';
}
echo '</ul>';
}
}

jsbin

关于PHP MySQL 显示按公共(public)字段分组的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4337639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com