Mysql
 sql >> Base de données >  >> RDS >> Mysql

PHP MySQL affiche plusieurs lignes regroupées par champs communs

<?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