sql >> Databasteknik >  >> RDS >> Mysql

PHP MySQL visar flera rader grupperade efter vanliga fält

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



  1. MySQL/PHP - sidnummer paginering Visa endast 10 sidor ibland

  2. Datahantering med Python, SQLite och SQLAlchemy

  3. Hur man delar upp en resulterande kolumn i flera kolumner

  4. vad är materialiserade åsikter i oracle?