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) ); 
3
  • possible duplicate of 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... Commented Oct 23, 2013 at 18:22
  • usort is your friend. Commented Oct 23, 2013 at 18:23
  • @Wrikken: array_multisort is one of those functions that I've never quite figured out how to use. Commented Oct 23, 2013 at 18:26

2 Answers 2

1

I like to use usort to solve these problems.

$sortKey = 1; usort($arr1, function($a, $b) use($sortKey){ return $a[$sortKey] - $b[$sortKey]; }); 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.