On 7/26/06, Angelo Zanetti <[EMAIL PROTECTED]> wrote:
Hi all,
So they way I want to sort these rows is by total, totalPaid,
totalUnpaid all descending.

Hi Angelo,

So the first question the list will ask is if the array of data is
coming from a database.  Because then you'd be urged to perform the
sorting from within your database query.

Barring that, you can use the usort() function to create custom
sorting.  What I've done below should do what you want, and I've tried
to generalize the functions a bit, so that you can mix descending and
ascending as you wish:

[code]
// Basic function for comparing arrays based on a particular column
function compareColumn($x, $y, $idx, $lessThan, $greaterThan)
{
if ( $x[$idx] == $y[$idx] )
 return 0;
else if ( $x[$idx] < $y[$idx] )
 return $lessThan;
else
 return $greaterThan;
}

// Calls compareColumn so that it sorts in descending order
function compareColumnDesc($x, $y, $idx)
{
        return compareColumn($x, $y, $idx, 1, -1);
}

// Calls compareColumn so that it sorts in ascending order
function compareColumnAsc($x, $y, $idx)
{
        return compareColumn($x, $y, $idx, -1, 1);
}

// Your customer comparison function.  The order in which you call each
// compareColumn*() is the ultimate order in which your multi-dim
array is sorted.
function compare($x, $y)
{
        // total is index 2 of the array
        $total = compareColumnDesc($x, $y, 2);
        if($total != 0) return $total;

        // totalPaid is index 3 of the array
        $totalPaid = compareColumnDesc($x, $y, 3);
        if($totalPaid != 0) return $totalPaid;

        // totalUnpaid is index 4 of the array
        $totalUnpaid = compareColumnDesc($x, $y, 4);
        if($totalUnpaid != 0) return $totalUnpaid;

        // arrays were equal
        return 0;
}

$record = array(
        array(1, 'marc', 12, 5, 7),
        array(5, 'berty', 30, 12, 18),
        array(7, 'sarah', 19, 12, 7)
        );

// sort your array
usort($record, 'compare');

// print sorted array
echo '<pre>';
var_export($record);
echo '</pre>';
[/code]


HTH,
John W

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to