0

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.

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh thank you, that was truly what I needed! Still learning things about array sorting in PHP, so I wasn't able to figure it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.