Re: Array Sorting

From: Date: Thu, 19 Jun 2003 09:43:43 +0000
Subject: Re: Array Sorting
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-152132@lists.php.net to get a copy of this message
Yes, simply don't return 0 when the manufacturers are equal, but continue with other checks: function cmp ($a, $b) {
    if ($a['cat'] == $b['cat']) {
// return 0; -- not anymore, but go on to compare manuf.
        if ($a['manufacturer'] == $b['manufacturer']) {
            if ($a['title'] == $b['title']) {
                // even title is the same, return 0
                return 0;
            }
            return ($a['title'] > $b['title']) ? -1 : 1;
        }
        return ($a['manufacturer'] > $b['manufacturer']) ? -1 : 1;
    }
    return ($a['cat'] > $b['cat']) ? -1 : 1;
} Ashley M. Kirchner wrote:
Marek Kilimajer wrote:
Use usort. This function should do the work:
Hey thanks! That worked like a charm, once I figured out that making the comparison < instead of > I would get an ascending sort instead of the descending one. Now, can I do multiple sorts? Like, sort on "cat" first, "manufacturer" next, and "title last"? Here's the array structure again: $i = 0;
$item[$i] = array( 'link'         => 'http://...',
                  'image'        => '/images/image.jpg',
                  'title'        => 'some title',
                  'price'        => '$14.00',
                  'cat'          => 'Frames',
                  'author'       => 'Pinochio',
                  'artist'       => '',
                  'asin'         => '010101',
                  'manufacturer' => 'Post'
                 ); $i++;
$item[$i] = array( 'link'         => 'http://...',
                  'image'        => '/images/something.jpg',
                  'title'        => 'this is fun',
                  'price'        => '$2.99',
                  'cat'          => 'Card',
                  'author'       => 'Mickey',
                  'artist'       => '',
                  'asin'         => '1116221',
                  'manufacturer' => 'Kraft'
                 ); $i++;
...etc., etc.


« previous php.general (#152132) next »