Page 1 of 1

List () function with NULL values

Posted: Tue Mar 04, 2008 9:30 pm
by Todlerone
Hello everyone and as usual thank-you in advance for any help and/or suggestions. I'm making a web page for my baseball league and again have come upon a little snag. I'm in the process of making the standings script. The values come from several joined MySQL tables resulting in a two dimensional array. My problem starts when I try to sort the array by the win% column only. I achieve my sort but since there are some NULL values my results are not great. Here is the sample of the code. How do I use the LIST() function with NULL values or is there an easier way. THANKS

Code: Select all

function reverse_compare($x,$y)
        {
            if ($x[8]==$y[8])//column [8] is winning% in array
                return 0;
            elseif ($x[8]>$y[8])//x>y gives descending values or x<y for ascending
                return -1;
            else
                return 1;
        }
 
usort ($standings,'reverse_compare');
 
for ($rows=0;$rows<$num_teams;$rows++)
    {
    while (list($key,$value)=each ($standings[$rows]))
    {
        echo "|$value  ";
    }
    echo '|<br />';
}

Re: List () function with NULL values

Posted: Tue Mar 04, 2008 10:26 pm
by Christopher
Use foreach() instead:

Code: Select all

for ($rows=0;$rows<$num_teams;$rows++)
    {
    foreach ($standings[$rows] as $value)
    {
        echo "|$value  ";
    }
    echo '|<br />';
}
On second thought, use implode():

Code: Select all

for ($rows=0;$rows<$num_teams;++$rows) {
    echo '|' . implode('|', $standings[$rows]) . '|<br />';
}

Re: List () function with NULL values

Posted: Tue Mar 04, 2008 11:43 pm
by Todlerone
arborint wrote:Use foreach() instead:

Code: Select all

for ($rows=0;$rows<$num_teams;$rows++)
    {
    foreach ($standings[$rows] as $value)
    {
        echo "|$value  ";
    }
    echo '|<br />';
}
On second thought, use implode():

Code: Select all

for ($rows=0;$rows<$num_teams;++$rows) {
    echo '|' . implode('|', $standings[$rows]) . '|<br />';
}
Thanks for the response arborint. I like the simplified code. However, I'm still getting the same output, ie, it isn't displaying any of my NULL fields. Could my problem be in my sorting technique?

Re: List () function with NULL values

Posted: Wed Mar 05, 2008 1:32 am
by Christopher
Yes, I thing usort() rebuilds the array with zero based indexes and may be removing your values. Try using your own sort algorithm that treats null the same as zero or ''. There is a sort function that takes a callback function for the comparison.

Re: List () function with NULL values

Posted: Wed Mar 05, 2008 2:16 am
by Benjamin
Might be easier to just sort it in MySQL. A quick google search for "mysql sort null fields" resulted in this as the first link: http://www.shawnolson.net/a/730/mysql-s ... -null.html