在计算PHP之后对结果进行排序

时间:2011-09-08 03:55:23

标签: php mysql count

这段代码效果很好,但我对如何订购感到失望。

示例输出:

点击3 Mozilla Firefox
点击2 Google Chrome
点击4 Internet Explorer
点击2 Apple Safari
点击1首歌曲

$result = mysql_query("SELECT * FROM WEB_STATS WHERE real_user NOT LIKE 'Bot'");
$duplicates = array();
while($row = mysql_fetch_array($result)) {
    $results = $row['user_browser'];

if (!array_key_exists($results, $duplicates)) {
    $browsersLive[] = $results;
    $duplicates[$results] = 1; ## mark that we've already output this records
    }
    }

foreach($browsersLive as $browserswive){
    $query = "SELECT COUNT(*) FROM WEB_STATS WHERE user_browser = '$browserswive'";
    $result = mysql_query($query) or die("Sorry, didn't work" . mysql_error());
    $browser_count = mysql_result($result, 0);

    if($browserswive == "Mozilla Firefox"){
    echo '<img alt="FireFox" height="32" src="images/fox-icons.png" width="32">Hits '.$browser_count.' '.$browserswive.'<br>';
}
    elseif($browserswive == "Internet Explorer"){
    echo '<img alt="Internet Explore" height="32" src="images/ie-icons.png" width="31">Hits '.$browser_count.' '.$browserswive.'<br>';
}
    elseif($browserswive == "Google Chrome"){
    echo '<img alt="Google Chrome" height="32" src="images/chrome-icons.png" width="32">Hits '.$browser_count.' '.$browserswive.'<br>';
}
    elseif($browserswive == "Apple Safari"){
    echo '<img alt="Apple Safari" height="32" src="images/safari-icons.png" width="32">Hits '.$browser_count.' '.$browserswive.'<br>';
}
    elseif($browserswive == "Opera"){
    echo '<img alt="Opera " height="33" src="images/opera-icons.png" width="33">Hits '.$browser_count.' '.$browserswive.'<br>';
}
}

2 个答案:

答案 0 :(得分:1)

将SQL调整为

SELECT user_browser, COUNT(*) as hits
FROM WEB_STATS 
WHERE real_user!='Bot'      <-- replace the NOT LIKE 'Bot'
GROUP BY user_browser
ORDER BY hits DESC;

你只需要查询一次,然后迭代结果

答案 1 :(得分:0)

尝试订购以下内容:

  • SUBSTRING_INDEX(colName,2) - &gt; HITS 2 Opera ===&gt; HITS 2
  • SUBSTRING(,INSTR('',colName)) - &gt; HITS 2 ==&gt; 2
  • CAST(签名) - &gt;将2转换为数字

全部放在一起

ORDER BY CAST(substring(substring_index(colName,2),INSTR(' ',colName)) AS SIGNED)

那应该做你想要的......