>我有一个数据库表,如下所示:
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的组字段。
问题已修改。
您需要
使用添加到查询中的 ORDER BY
语句获取结果。
SELECT id, igroup, title, url, text
FROM images
ORDER BY igroup;
警告:
请不要使用
mysql_*
函数来编写新代码。它们不再维护,社区已开始弃用过程。看到红框了吗?相反,您应该了解预准备语句并使用PDO或MySQLi。本文应提供有关决定使用哪个 API 的一些详细信息。对于 PDO,这是一个很好的教程。
示例代码:
$result = mysql_query(THE_STATEMENT_ABOVE);
$groups = array();
while ( $row = mysql_fetch_assoc($result) )
$groups[ $row['igroup'] ][] = $row;
这将建立一个漂亮的$groups
数组。要解析上面创建的数组,可以使用迭代器或简单的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
作为字段名称,因为它是保留的 MySQL 单词之一。
编辑:我还将字段名称更正为igroup
。