我正在试图弄清楚如何列出公司的CATEGORY和BRAND,其布局看起来与此类似:
COMPANY 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
答案 0 :(得分:5)
<?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> </li>';
}
echo '</ul>';
}
}
答案 1 :(得分:0)
只需获取所有内容并将其放入php中的哈希值,即
行$rs = mysql_query("Select * from myTable");
$results = array();
while($row = mysql_fetch_assoc($rs)) {
$results[$row['COMPANY']][$row['CATEGORY']][] = $row['BRAND'];
}
$results
将包含类似
array(
'Company 1' => array(
'Category 1' => array('Brand X', 'Brand Y')
... etc
)
尝试var_dump($results)
让它更有意义