在MySQL中对MySQL进行排序...? [英] Sorting MySQL results in PHP...?
问题描述
我的网站上有一个页面,上面列出了一堆产品,每个产品都有用户评分.我使用一个查询为每个产品提取一些数据点(详细信息查询"),并使用第二个查询返回每个产品的平均用户评分(评分查询").
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").
我想将每个产品的用户评分附加到详细信息查询"结果集中,然后按评分降序排序.我已经在Stack Overflow,php.net等上阅读了很多条目,我认为我需要使用带有自定义函数的usort(),但是每次我将MySQL结果传递给usort()时,我都会得到一个php错误,说我传递给usort()的对象不是数组.例如,我尝试过:
I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:
$data = mysql_fetch_array($details_query);
usort($data,"compare");
执行上述操作将引发错误,指出$ data不是数组.我究竟做错了什么?
Doing the above will throw an error saying $data isn't an array. What am I doing wrong?
此外,如果有人对如何完成此操作有其他建议,我将非常感谢.由于某种原因,我在这段时间过得很艰难...
Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...
谢谢!
推荐答案
您误用了MySQL函数-mysql_fetch_array不接受SQL查询,而是接受MySQL结果资源:
You're mis-using the MySQL functions - mysql_fetch_array doesn't take a SQL query, it takes a MySQL result resource:
http://php.net/manual/en/function. mysql-fetch-array.php
所以您想要类似的东西:
So you want something like:
$all_data = array();
$sql = "SELECT blah FROM blah";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$all_data[] = $row;
}
// $all_data is now a 2-D array with all your data.
usort($all_data, "compare");
这篇关于在MySQL中对MySQL进行排序...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!