Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a multi-dimensional array by value?

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'
    )
);
like image 694
Chris Ford Avatar asked Jul 19 '10 14:07

Chris Ford


People also ask

Can we sort multidimensional array?

A two-dimensional or 2D array is a collection of columns and rows. Programmers can randomly access the 2D array elements or each cell individually by utilizing their indexes. With the help of sorting, array elements are arranged according to the requirements, whether in ascending or descending order.

How do you sort an array by value?

PHP - Sort Functions For Arrayssort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.

How do you sort a multidimensional array in Python?

Use sorted() with a lambda function to sort a multidimensional list by column. Call sorted(iterable, key=None) with key set to a lambda function of syntax lambda x: x[i] to sort a multidimensional list iterable by the i th element in each inner list x .

Which function sorts multiple array at once?

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.


1 Answers

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'];
like image 74
Felix Kling Avatar answered Oct 12 '22 23:10

Felix Kling