我需要把我的结果按顺序从mysql中获取

时间:2012-08-06 20:27:11

标签: php arrays json classification

我有一个如下数据库表:

id | igroup | title     | url          | text
1  |   gr1  | Title 1   | urltoimage1  | text1
2  |   gr1  | Title 2   | urltoimage2  | text2
3  |   gr2  | Title 3   | urltoimage3  | text3
4  |   gr2  | Title 4   | urltoimage4  | text4

我的意思是,我希望有一个多维数组(对于上面的结构),如下所示;

$result[gr1] = [Title 1|urltoimage1][Title 2|urltoimage2]
$result[gr2] = [Title 3|urltoimage3][Title 4|urltoimage4]

最后,我将通过JSON将此$result数组发送到页面。

因此,在我的页面中,我会为分类图库安排这些值,例如:

Group 1(caption text)
--------
image1 image2 (clickable images)

Group 2(caption text)
--------
image3 image4 (clickable images)

编辑:我通过igroup修正了组字段。

问题已修订。

1 个答案:

答案 0 :(得分:2)

您需要使用添加到查询中的ORDER BY语句来获取结果。

SELECT id, igroup, title, url, text
FROM images
ORDER BY igroup;
  

警告:

     

请不要使用mysql_*函数来编写新代码。它们已不再维护,社区已开始deprecation process。请参阅red box

     

相反,您应该了解prepared statements并使用PDOMySQLiThis article应该提供有关决定使用哪个API的一些详细信息。对于PDO,这里是good tutorial

示例代码:

$result = mysql_query(THE_STATEMENT_ABOVE);

$groups = array();
while ( $row = mysql_fetch_assoc($result) )
    $groups[ $row['igroup'] ][] = $row;

这将构建一个不错的$groups数组。要解析上面创建的数组,您可以使用Iterators或简单foreach结构。

foreach ( $groups as &$one_group ) {
    print("Group 1: <br>");

    foreach ( $one_group as &$one_image ) {
        // Here you have the contets of the previously fetched $row rows of the result.
        print('<a href="' .$one_image['url']. '">' .$one_image['title']. '</a><br>');
    }
}

这将为您提供如下所示的良好输出:

Group 1:
Image 1 (clickable)
Image 2 (clickable)

Group 2:
Image 3 (clickable)
Image 4 (clickable)

不再适用:此外,您应该避免使用GROUP作为字段名称,因为它是reserved MySQL words之一。

修改:我还将字段名称更正为igroup