Php 我需要把我的结果按顺序从mysql中获取
我有一个如下所示的数据库表:Php 我需要把我的结果按顺序从mysql中获取,php,arrays,json,classification,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
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.*
函数来编写新代码。它们不再得到维护,社区已开始恢复。看到了吗
相反,您应该了解并使用或。应该给出一些关于决定使用哪个API的细节。对于PDO,这里有一个例子
示例代码:
$result = mysql_query(THE_STATEMENT_ABOVE);
$groups = array();
while ( $row = mysql_fetch_assoc($result) )
$groups[ $row['igroup'] ][] = $row;
这将建立一个漂亮的$groups
数组。要解析上面创建的数组,可以使用或使用简单的构造
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>');
}
}
不再适用:此外,您应该避免使用组
作为字段名,因为它是一个
编辑:我还将字段名更正为
igroup
group
是mysql中的保留字。在排序之前,您可能需要为该列指定一个别名。@Blaine-按组排序field@Matt-让我更正有问题的名称选择id,`group`as myGroup。。。order by myGroup
我不是在说MySql中的order。我想获取结果并将它们放入一个数组(结构有问题)中,然后通过JSON发送到页面。。谢谢。我只想再问一个关于你的解决方案的问题。我在db中有6个图像,当我执行你的函数时,6个图像链接被正确放置,但是还有一行返回NULL。为什么会这样?再次感谢。在while(){}
构造之后,在$groups
上调用var\u dump()
,然后打开输出。我们会调查的。但是值是土耳其语:)如果您的组有一个标题
字段,您只需更改打印(“组1:
”)代码>行以满足您的需要。
Group 1:
Image 1 (clickable)
Image 2 (clickable)
Group 2:
Image 3 (clickable)
Image 4 (clickable)