user1165983
user1165983

Reputation: 3

Sorting a Multi-Dimensional Array with Multiple Keys in PHP

Well I am trying to sort some data in PHP. Here is an example of the array(the first column representing ids I want to still be associated with their respective values in each row):

0 1 2.0
1 15 20.0
2 15 5.5
3 15 55.1
4 2 22.3
5 20 70.8
6 2 8.2

First I would like to arrange the rows in an order where the values in the second column are in decending order:

5 20 70.8
1 15 20.0
2 15 5.5
3 15 55.1
4 2 22.3
6 2 8.2
0 1 2.0

Then, keeping those with the second column still in its arrangement, by each set of rows with the same value in the second column, arrange the third values in ascending order:

5 20 70.8
2 15 5.5
1 15 20.0
3 15 55.1
6 2 8.2
4 2 22.3
0 1 2.0

I have tried some things with the array sorting functions for PHP, however I can't figure out how to do both those operations while still maintaining row association.

Upvotes: 0

Views: 573

Answers (1)

Jim H.
Jim H.

Reputation: 5579

One way is to use the usort function to create a custom sorting routine. There is quite a large number of ways to sort arrays in PHP depending on how you want the data sorted, multi-dimensionality, key sorts, etc. This snippet sorts based on the input and output requirements stated above.

$vals = array(
    array('id' => 0, 'val1' => 1, 'val2' => 2.0),
    array('id' => 1, 'val1' => 15, 'val2' => 20.0),
    array('id' => 2, 'val1' => 15, 'val2' => 5.5),
    array('id' => 3, 'val1' => 15, 'val2' => 55.1),
    array('id' => 4, 'val1' => 2, 'val2' => 22.3),
    array('id' => 5, 'val1' => 20, 'val2' => 70.8),
    array('id' => 6, 'val1' => 2, 'val2' => 8.2)
    );

usort($vals, 'sortfn');

function sortfn($a, $b)
{
    if($a['val1'] == $b['val1'])
        return ($a['val2'] > $b['val2']);
    else
        return ($a['val1'] < $b['val1']);
}

var_dump($vals);

Upvotes: 2

Related Questions