Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

MySQL-Zeilen in PHP nach Firma, Kategorie und Marke gruppieren

Ein sauberer Weg ist, die Daten in SQL nach allen Hierarchieebenen zu sortieren und dann in PHP in ein mehrdimensionales Array zu überführen.

$result = $pdo->query(
    "SELECT * FROM some_table ORDER BY company, category, brand"
);

$companies = [];
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $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 '</li>';
    }
    echo '</ul>';
}

Die verkettete Array-Zuweisung erzeugt jede Ebene nur bei Bedarf. htmlentities() schützt die Ausgabe.