如何在查询完成后对mysql结果集进行排序

时间:2010-12-27 09:41:14

标签: php mysql sorting

我正在为具有2个参数的mysql数据库编写查询。

它是一个基本的搜索,但问题是我想根据选择对结果的顺序进行排序。 所以在我点击了搜索按钮并且浏览器显示了结果集后,我想按 expiration-date price 依赖于我点击的按钮。

   //SELECTION DATA FORM 
   <form action="EVENTS_SELECTION.PHP">
     <select name="Type">
     <option value="">SPORT
     <option value="">CULTURE       
     <option value="">LEISURE
     <option value="">GASTRONOMY
     </select>  

     <select name="WHERE">
     <option>ROME ALL
     <option>ROME SOUTH
     <option>ROME WEST
     <option>ROME EAST
     <option>ROME NORTH
     </select>

     <input type="submit" value="search">   
 </form> 

我怎样才能实现? 谢谢 卢卡

2 个答案:

答案 0 :(得分:0)

如果您想在搜索后排序,可以使用usort()功能:

function myComparer($a, $b)
{
    if ($GLOBALS['SEARCH_TYPE'] == 'PRICE')
    {
        $valueA = floatval($a['price']);
        $valueB = floatval($b['price']);
    }
    else ($GLOBALS['SEARCH_TYPE'] == 'EXPIRATION-DATE')
    {
        // time string to UNIX timestamp integer value
        $valueA = strtotime($a['expiration_date']);
        $valueB = strtotime($b['expiration_date']);
    }

    if ($valueA == $valueB) {
        return 0;
    }

    return ($valueA < $valueB) ? -1 : 1;
}

include './get_search_type.php';
// is stored in array $GLOBALS['SEARCH_TYPE']

include './get_search_result.php'; xyz is the field name
// is stored in array $GLOBALS['SEARCH_RESULT'][xyz]

usort($GLOBALS['SEARCH_RESULT'], myComparer);

btw:在我看来,最好生成一个动态查询来按DBMS排序(这更容易):

if ($GLOBALS['SEARCH_TYPE'] == 'PRICE')
{
    $query = "SELECT * FROM Products ORDER BY price;";
}
else ($GLOBALS['SEARCH_TYPE'] == 'EXPIRATION-DATE')
{
    $query = "SELECT * FROM Products ORDER BY expiration_date;";
}

答案 1 :(得分:0)

[服务器端] 将php查询结果存储到如下数组中:

// if you want to sort by column 'name', store them by format: $dataset[{pid}] = {name};
// pid  name
//  1   test1
//  2   alpha1
//  5   candy1
while (...) // read query result
{
    $dataset[$row['pid']] = new array($row['name'] => $row);
}    
// now, use sort()
sort($dataset);

// then foreach array to get sorted data;
foreach ($datasetas $key => $val) {
    echo $val."\n";
}

[客户端] 读取数据并按JSON格式和响应存储它们。然后,在您的页面中,使用javascript json库对它们进行排序。