views:

62

answers:

2

I have an array as following and I want to order that array by the value of the key "attack". First keys of the arrays (15, 13, 18) are ID of some certain item from database, so I don't want these keys to be changed when the array is sorted. Any help would be greatly appreciated.

This is the array:

$data = array('15' => array('attack' => '45', 'defence' => '15', 'total' => '10'),
          '13' => array('attack' => '25', 'defence' => '15', 'total' => '10'),
          '18' => array('attack' => '35', 'defence' => '15', 'total' => '10')
    );
+3  A: 

Use uasort():

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Example:

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

uasort($data, 'cmp');

If the values are always strings, you can also use strcmp() in the cmp() function:

function cmp($a, $b) {
    return strcmp($a['attack'], $b['attack']);
} 

Update:

To sort in descending order you just have to change the return values:

return ($a['attack'] < $b['attack']) ? 1 : -1;
//                                     ^----^

or to pick up @salathe's proposal:

return $b['attack'] - $a['attack'];
Felix Kling
Boo for overly complicated callback. `$a['attack'] - $b['attack'];` would suffice.
salathe
@salathe: True, this would be more efficient. But this is more compliant with the examples of the documentation.
Felix Kling
I tried your solution but this only prints 1 to the screen.
Chris Ford
@Chris: `uasort` sorts the array in place. It returns `true` on success (mentioned in the documentation I linked to). If you want to print the result, you have to print the array.
Felix Kling
Of course, I print the array using print_r but it only prints 1 to the screen.
Chris Ford
@Chris: Not for me. I get the sorted array... must be something else in your code.
Felix Kling
Sorry, my bad. I saw I was printing something else. I have one more question. How do I sort the value by descending order?
Chris Ford
@Chris: Please see my updated answer.
Felix Kling
Thank you for all the answers.
Chris Ford
@Felix -- I guess the docs could offer more varied examples and/or state that the values don't have to be in the set -1, 0 and 1.
salathe
A: 
$data = array('15' => array('attack' => '45', 'defence' => '15', 'total' => '10'),
          '13' => array('attack' => '25', 'defence' => '15', 'total' => '10'),
          '18' => array('attack' => '35', 'defence' => '15', 'total' => '10')
    );

uasort($data, 'cmp');

function cmp($x, $y) {
    if ($x['attack'] > $y['attack']) {
        return 1;
    } elseif ($x['attack'] < $y['attack']) {
        return -1;
    }
    return 0;
}

print_r($data);

PRINTS:

Array
(
    [13] => Array
        (
            [attack] => 25
            [defence] => 15
            [total] => 10
        )

    [18] => Array
        (
            [attack] => 35
            [defence] => 15
            [total] => 10
        )

    [15] => Array
        (
            [attack] => 45
            [defence] => 15
            [total] => 10
        )

)
sberry2A