2010-12-02 61 views
1

我試圖找出如何列出公司類別的,品牌的,在佈局將類似於此:PHP MySQL的顯示由公共字段分組多行

公司1

  • 類別1:
    BRAND X
    品牌Y
    BRANDž

  • CATEGORY 2
    品牌
    BRAND乙
    C品牌

  • CATEGORY 3
    品牌
    BRAND 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

@ajreal感謝您的編輯! – 3r1c 2010-12-02 20:49:24

回答

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>&nbsp;</li>'; 
    } 
    echo '</ul>'; 
    } 
} 

jsbin

+0

這太好了。謝謝。 – 3r1c 2010-12-02 20:44:00

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)使其更有意義

+0

感謝您的信息。 – 3r1c 2010-12-02 20:47:29