drake035
drake035

Reputation: 2877

Sorting a non-associative, multidimensional array

I found lots of info about sorting associative arrays but little about sorting non-associative ones. My array is structured/populated this way:

$my_array = array();
$my_array[0][0] = 'whatever3';
$my_array[0][1] = 3
$my_array[1][0] = 'whatever2';
$my_array[1][1] = 2
$my_array[2][0] = 'whatever1';
$my_array[2][1] = 1

I want to sort it by the second value to get:

$my_array[0][0] = 'whatever1';
$my_array[0][1] = 1;
$my_array[1][0] = 'whatever2';
$my_array[1][1] = 2;
$my_array[2][0] = 'whatever3';
$my_array[2][1] = 3;

How can this be achieved considering my array isn't associative?

Upvotes: 0

Views: 247

Answers (1)

JuniorCompressor
JuniorCompressor

Reputation: 20015

What about:

usort($combined, function ($a, $b) { return $a[1] - $b[1]; });

With usort you provide a custom comparison function that must return:

  • 0, if the elements must be considered equal.
  • a negative number, if the first element must be considered smaller than the second one.
  • a positive number, if the first element must be considered greater than the second one.

In this case, we choose to compare the second element of each item of $combined array.

Upvotes: 2

Related Questions