0

I tried to search and found this:

Sort an array by a child array's value in PHP

But the function does not work in my case:

                $sorted = array();
                foreach($players as $player)
                {
                    $p = Model::factory('user');
                    $p->load($player['id']);

                    $sorted[] = array('id' => $player['id'], 'username' => $p->get_username());
                }

How can i sort the array alphabetic after the username?

The function,

function cmp($a, $b) {
        if ($a['username'] == $b['username']) {
                return 0;
        }
        return ($a['username'] < $b['username']) ? -1 : 1;
}

and then calling usort($sorted,"cmp"); will not work out for me (getting error undefined index[2])..

And is there any way to choose whether it should be sorting descending or ascending?

Community
  • 1
  • 1
Karem
  • 17,615
  • 72
  • 178
  • 278

2 Answers2

0

Because the index 2 doesn't exist in your array. You should use $a['username'] or $a['id'], but i guess you want to sort on username so then you would use $a['username'].

gitaarik
  • 42,736
  • 12
  • 98
  • 105
0

The 'cmp' function will be:

// $param - the parameter by which you want to search
function cmp(&$a, &$b, $param) {
    switch( $param ) {
        case 'id':
            if ( $a['id'] == $b['id'] ) {
                return 0;
            }

            return ( $a['id'] < $b['id'] ) ? -1 : 1;
            break;
        case 'username':
            // string comparison
            return strcmp($a['username'], $b['username']);
            break;
    }
}

// this is the sorting function by using an anonymous function
// it is needed to pass the sorting criterion (sort by id / username )
usort( $sorted, function( $a,$b ) {
    return cmp( $a, $b, 'username');
});
web-nomad
  • 6,003
  • 3
  • 34
  • 49
  • Cant i pass a parameter to the cmp function, so I can mention what index to look for? In this code, 'username'. So usort($sorted, cmp('username')); and then if i would like to look for id instead, usort($sorted, cmp('id')); , etc ? – Karem Apr 05 '12 at 10:27
  • Thanks for reply.How would i call it ? usort($sorted, cmp('username')); wont work out – Karem Apr 05 '12 at 10:38
  • @karem - i have modified my answer to include the comparison filter. Basically, it makes use of the **anonymous(lambda) functions**[link](http://php.net/manual/en/functions.anonymous.php) in PHP . You will have to have php version >= 5.3 – web-nomad Apr 05 '12 at 11:10