Wrox Home  
Search P2P Archive for: Go

  Return to Index  

pro_php thread: MySQL - Order by Calculated Value


Message #1 by Roger Jacobs <raj@l...> on Tue, 19 Mar 2002 14:33:00 -1000
Brilliant!

I had overlooked usort and you have changed my life.

Thanks,

Roger





>I don't know if it's possible to sort them in the mysql query.
>
>Within PHP, you should be able to sort them by using your own comparison
>function and calling usort() on the array of results.
>
>for example, if your query returned the 4 rows you listed in your email,
>then $results would be an array holding all four rows:
>
>$results[0][lname] = "Atchison";
>$results[0][org]   = "";
>$results[1][lname] = "Williams";
>$results[1][org]   = "Beta Testers, Inc.";
>$results[2][lname] = "Cafferty"
>$results[2][org]   = "";
>$results[3][lname] = "Jones";
>$results[3][org]   = "Dynamic Processing, Inc.";
>
>// $lhs and $rhs are going to be values for $results[x], which
>// evaluate to arrays containing TWO fields -- ['org'] and ['lname']
>function my_strange_comparison_function($lhs, $rhs)
>{
>    if($lhs['org'] != "")
>       $row1_cmpstr = $lhs['org'];
>    else
>       $row1_cmpstr = $lhs['lname'];
>
>    // same thing for rhs.  Here's another way to write the if/else
>    $row2_cmpstr = ($rhs['org'] != "")? $rhs['org'] : $rhs['lname'];
>
>    // use any string comparison you want, I just put strcasecmp()
>    // because it exists. =)
>    return strcasecmp($row1_cmpstr, $row2_cmpstr);
>}
>
>
>
>NOTE:  I didn't test this code, but I don't see any reason why it shouldn't
>work.  The only check I think should be made that's not there is to see if
>$lhs['org'] is actually not set (NULL instead of just "").
>
>
>Good luck,
>
>Nik
>
>


--------------ROGER JACOBS - DATA SYSTEMS CONTRACTOR ----------------
DataSpace Industries                    mailto:raj@o...
4491 Rice Street, Suite 102             http://www.omnisphere.com
Lihue, HI  96766                        See Kauai Products & Services:
xxx-xxx-xxxx      FAX-246-4725           http://www.lauhala.com






  Return to Index