This question has already been answered:

Hello. There is an array:

array(3)=> array(2)=> 'count'=10; 'value'="some string"; array(2)=> 'count'=100; 'value'="another string"; array(2)=> 'count'=2; 'value'="last string"; 

I want to sort by the 'count' key to get the following array on output:

 array(3)=> array(2)=> 'count'=100; 'value'="another string"; array(2)=> 'count'=10; 'value'="some string"; array(2)=> 'count'=2; 'value'="last string"; 

How is this possible to do?

Reported as a duplicate by members of Visman , tutankhamun , Firepro , aleksandr barakin , cheops 15 Sep '16 at 5:19 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • @Visman such duplicates in the week for two here appear ... - Naumov
  • @Naumov, I suggest to mark all duplicates;) - Visman
  • @Visman There are already 100 of them already marked each time: D even on mete there was a topic on this topic, forgive me for tuftology - Naumov

3 answers 3

Documentation

 function cmp($a, $b) { if ($a['count'] == $b['count']) { return 0; } return ($a['count'] < $b['count']) ? -1 : 1; } $myArray = array(...); usort($myArray, "cmp"); 

    Use the power of sorting functions using a given comparison algorithm.

     $arr = [ [ 'count' => 10, 'value' => 'some string' ], [ 'count' => 100, 'value' => 'another string' ], [ 'count' => 2, 'value' => 'last string' ] ]; usort($arr, function($a, $b){ return $b['count'] <=> $a['count']; }); 

    https://repl.it/D90r

    PS The Spaceship operator is available with PHP 7. It’s easy to replace, if necessary, like homework :)

      You can still so, but the answer above is more compact and convenient

       $arr = array( array( 'count' => '10', 'name' => 'some string' ), array( 'count' => '100', 'name' => 'some 2string' ), array( 'count' => '526', 'name' => 'some 3string' ) ); for ($i=0; $i < count($arr); $i++) { for ($j=0; $j < count($arr); $j++) { $count = $arr[$j]['count']; $next_count = $arr[$j+1]['count']; if($count < $next_count){ $temp = $next_count; $arr[$j+1]['count'] = $count; $arr[$j]['count'] = $temp; } } } 

      Result

       Array ( [0] => Array ( [count] => 526 [name] => some string ) [1] => Array ( [count] => 100 [name] => some 2string ) [2] => Array ( [count] => 10 [name] => some 3string ) )