开发者

Placing a specific record at end of a query

开发者 https://www.devze.com 2023-02-12 21:39 出处:网络
In the query I have order by name (alphabetically), stick the query in $res, and then loop over the results.

In the query I have order by name (alphabetically), stick the query in $res, and then loop over the results.

while($rs = mysql_fetch_assoc($res)){
    echo $rs['name'];
}

Now in that while loop there is a "webmaster" name. I need to take "Webmaster" and place it at the end of the loop (so it开发者_StackOverflow中文版 echoes out last) or place "Webmaster / Affiliate ProgramsWebshops" in $res (at the end of the query before hitting the while loop.


easiest way would be to edit your query and change the ordering from:

ORDER BY
  name

to

ORDER BY
  IF(name LIKE 'webmaster',1,0),
  name

note: this IF is mysql-syntax - you havn't posted wich database you're using. on postgres it would be something like (not 100% sure):

ORDER BY
  CASE WHEN name ILIKE 'webmaster' THEN 1 ELSE 0 ,
  name

EDIT to explain this: by changing the order this way, it's like putting an additional column to the ordering that contains 1 if the name is "webmaster" or 0 in every other case. by ordering by this "column" first, the "webmaster" is always at the end (or: all "webmaster"s - if there are more than one)


Maybe something like this:

$webmasterArray = array();
while($rs = mysql_fetch_assoc($res))
{
    if($rs['name'] == "webmaster")
        $webmasterArray = $rs;
    else
        echo $rs['name'];
}
if($webmasterArray)
    echo $webmasterArray['name'];
0

精彩评论

暂无评论...
验证码 换一张
取 消