开发者

How do I get unique values from a column and group them with values from another column?

开发者 https://www.devze.com 2023-02-04 03:18 出处:网络
I want to group items together based on the year. It would be displayed in a table like 2010 -item 1 -item 2

I want to group items together based on the year. It would be displayed in a table like

 2010
   -item 1 
   -item 2 
   -item 3
 2009
   -item 4
   -item 5 
   -item 6

How开发者_如何学Go would i do this using php and mysql?


you could put each database row into an associative array, with the year as the key, then iterate the array to construct your list

  $yearItems = array();
  while ($row = mysql_fetch_assoc($result)) {
    $yearItems[$row['year']][] = $row;
  }

  foreach($yearItems as $year=>$items)
  {
    echo $year;

    echo "<ul>";
    foreach($items as $item)
    {
      echo "<li>$item</li>";
    }
    echo "</ul>";
  }


SELECT year(datefield) as year, name_of_item
FROM yourtable
ORDER BY year, name_of_item

would be the basic query structure, then

$first = true;
$previous_year = null;

echo "<ul>";
while($row = mysql_fetch(...)) {
    if ($previous_year != $row['year']) {
       ... got a new year, start a new list
       if (!$first) {
            echo "</ul>";
       }
       $first = false
       $previous_year = $row['year']
    }
    echo "<li>", $row['name_of_item'], "</li>"
}
echo "</ul>"
0

精彩评论

暂无评论...
验证码 换一张
取 消