Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort arrays inside an array? [duplicate]

Tags:

php

I need to sort arrays inside an array of array based on one of the array's array value.

For example:

$data = array( array( 1, "Article One", 132, 12402773, 3 ),
               array( 2, "Article Two", 251, 12519283, 5 ),
               array( 3, "Article Three", 107, 12411321, 3 ),
               array( 4, "Article Four", 501, 12228135, 4 ) );

By default, if I print the 2nd element of each array:

  • Article One
  • Article Two
  • Article Three
  • Article Four

I need to sort it in a descending order by the 3rd element of the child-array.

So it would be like this:

  • Article Four
  • Article Two
  • Article One
  • Article Three

Because 501 > 251 > 132 > 107.

Any suggestion?

like image 391
Yana D. Nugraha Avatar asked Dec 29 '22 07:12

Yana D. Nugraha


2 Answers

I typically use a usort() for this:

function compare($a, $b) {
    return ($a[2] > $b[2]);
}

usort($data, 'compare');
like image 109
willoller Avatar answered Dec 31 '22 20:12

willoller


array_multisort :)

like image 36
Tor Valamo Avatar answered Dec 31 '22 21:12

Tor Valamo