0

I have this array and I need to sort it, first by "key_1" and (in case of more of one similar values in "key_1") sort it by "key_2" ... how can I do this, any idea?

Thanks!

$my_array[0]['key_1'] = 2;
$my_array[0]['key_2'] = 300;

$my_array[1]['key_1'] = 2;
$my_array[1]['key_2'] = 100;

$my_array[2]['key_1'] = 1;
$my_array[2]['key_2'] = 100;
0

1 Answer 1

1

Here is a simple solution :

function my_sort($a, $b) {
  if ($a['key_1']==$b['key_1']) {
    if ($a['key_2']==$b['key_2']) {
      return 0;
    } else {
      return ($a['key_2']>$b['key_2']) ? 1 : -1;
    }
  } else {
    return ($a['key_1']>$b['key_1']) ? 1 : -1;
  }
}

usort($my_array, 'my_sort');
Sign up to request clarification or add additional context in comments.

Comments

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.