0

I have an array fetched from mysql database tables of type. I want to sort it in order of particular value.

$arr1=array(array(12, 8, 5, 34),
        array(54, 87, 32, 10),
        array(23, 76, 98, 13),
        array(53, 16, 24, 19));

How can i sort it by value? Like sorting by 2nd value should result to.

$arr1=array(array(12, 8, 5, 34),
        array(53, 16, 24, 19),
        array(23, 76, 98, 13),
        array(54, 87, 32, 10));
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
Daman
  • 343
  • 1
  • 4
  • 15
  • possible duplicate of [How do I sort a multidimensional array in php](http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php), then again, if you fetch it from a database, the database probably can do it faster for you... – Wrikken Oct 23 '13 at 18:22
  • [`usort`](http://php.net/usort) is your friend. – Rocket Hazmat Oct 23 '13 at 18:23
  • @Wrikken: `array_multisort` is one of those functions that I've never quite figured out how to use. – Rocket Hazmat Oct 23 '13 at 18:26

2 Answers2

1

I like to use usort to solve these problems.

$sortKey = 1;
usort($arr1, function($a, $b) use($sortKey){
    return $a[$sortKey] - $b[$sortKey];
});
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
1

Got to agree with @RocketHazmat, array_multsort is a royal pain in the backside. usort is much easier to follow but I thought I'd have a go anyway:

$sortKey = 1;
array_multisort(array_map(function($v) use($sortKey){
    return $v[$sortKey];
}, $arr1), $arr1);

It only took 20 minutes... :(

Here's a demo: http://ideone.com/2rZYIz

Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
Emissary
  • 9,018
  • 8
  • 50
  • 58