简体   繁体   English

按列将MySQL结果分组

[英]Group MySQL Result by column

I have a problem on output the MySQL result to HTML. 我在将MySQL结果输出到HTML时遇到问题。 I had a MySQL result which returns: 我有一个MySQL结果返回:

| title        | category_name | from_where |
---------------------------------------------
| Title num 1  | Journal       | iidl_file  |
---------------------------------------------
| Title num 2  | Books         | iidl_file  |
---------------------------------------------
| Title num 3  | Announcement  | iidl_post  |
---------------------------------------------
| Title num 4  | News          | iidl_post  |
---------------------------------------------

How can I preview this data in HTML like this: 我如何像这样预览HTML中的数据:

iidl_file
 - Title num 1 (Journal)
 - Title num 2 (Books)

--------------------------

iid_post
 - Title num 3 (Announcement)
 - Title num 4 (News)

This is what I would do: 这是我会做:

SELECT `title`, `category_name`, `etc` FROM `table_name` ORDER BY `from_where`;

If you have many records, you will benefit greatly from making sure there is an index on the from_where column. 如果您有很多记录,那么确保from_where列上有一个索引将对您有很大的from_where

Here is some pseudo-code: 这是一些伪代码:

$groups = array();
foreach ($rows as $row) {
    $from_where = $row['from_where']
    if (! isset($groups[$from_where])) {
        $groups[$from_where] = array();
    }
    $groups[$from_where][] = $row;
}

Now your $groups will contain arrays keyed by the from_where column. 现在,您的$groups将包含由from_where列键控的数组。

Doing this, you actually don't have to even issue the ORDER BY in the query. 这样做,您实际上甚不必在查询中发出ORDER BY。

Just an idea, just use normal mysql result loop with a code like this, not tested but hope it will help 只是一个想法,只需将普通的mysql结果循环与这样的代码一起使用,未经测试,但希望它会有所帮助

$from_all = array();
$from_all[$from_where][] = array('title'=>$title,'category_name'=>$category_name)

then 然后

foreach($from_all as $from_where=>$array) {
    echo $from_where
    foreach($array as $row) {
        echo $row['title'];
        echo $row['category_name'];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM