0

I have a listings table, and each listing has column called 'top'. Basically, if top is not null, I want that listing to show up first, then the others.

Right now, my code is like this:

foreach ($results as $result):
    echo $result->name;
endforeach;

This will show me everything, but I want the rows with 'top' not null to show up first. What's the best way to go about this?

4

4 回答 4

5

Can't you apply an ORDER BY to the query that feeds $results?

于 2012-04-25T20:28:29.023 回答
0

I agree with Aaron... the best thing to do is to order them so that they are first in the query.

If for some reason you couldn't do that you could do a few other things:

  1. Sort the object or array in PHP... may have to use a custom function .. if that's the case see: Sort Object in PHP

  2. Grab the rows that only have the NULL first, print them, then grab the ones that aren't null.

  3. You could loop through the array twice. First only printing the NULLs, then again to print the others.

于 2012-04-25T20:33:08.053 回答
0

Try

foreach ($result as $row){

Then specify each element you want in order.

echo $row['top']

echo $row['your next data row']... and have them space exactly how you want.

And if you need it formated, try using <pre> first.

You can also add a if statment.

$data = $row['top'] if($top == 1) { then echo this } else {echo the values that are null }

于 2012-04-25T20:37:17.810 回答
0

Based on your comment below @Aaron Bertrand's answer, you would need an order clause in your sql like:

ORDER BY ISNULL(`top_ad`), the_rest_of_your_order_clause
于 2012-04-25T20:42:29.570 回答