-1

i have the following array and i want to sort this array in descending order on the base of the "count" index value in php. i have used the following code but it is not working for me. please give me hint to sort array in descending order.

Array:-

Array ( [0] => Array ( [text] => this is text [count] => 0 ) 
        [1] => Array ( [text] => this is second text [count] => 2 ) 
        [2] => Array ( [text] => this is third text [count] => 1 )
      )

I have tried the following code.

function sort_count($a, $b) {
    return $a['count'] - $b['count'];
}
$sorted_array = usort($array, 'sort_count');
usman khalid
  • 75
  • 3
  • 14

4 Answers4

2

Ascending..

usort($your_array, function($a, $b) {
   return $a['count'] - $b['count'];
});

Descending..

usort($your_array, function($a, $b) {
   return $b['count'] - $a['count'];
});

Example here

Kylie
  • 11,421
  • 11
  • 47
  • 78
0

you can use core php functions like

rsort ($array)
arsort($array) 

also you should read this in php manual http://php.net/manual/en/array.sorting.php

Dev_meno
  • 124
  • 14
0

Here is the solution:

$a1 = array (array ( "text" => "this is text", "count" => 0 ), 
    array ( "text" => "this is text", "count" => 1 ),
    array ( "text" => "this is text", "count" => 2 ),
  );
usort($a1 ,sortArray('count')); 
function sortArray($keyName) {
  return function ($a, $b) use ($keyName) {return ($a[$keyName]< $b[$keyName]) ? 1 : 0;
    };
}
print_r($a1);
Indrajit
  • 405
  • 4
  • 12
0

Try this:

Note: Checking your equality acts as an added advantage.

function sort_count($a, $b) {
   if ($a['count'] === $b['count']) {
      return 0;
   } else {
       return ($a['count'] > $b['count'] ? 1:-1);
   }
}
$sorted_array = usort($array, 'sort_count');

echo "<pre>";

print_r($array);

echo "</pre>";

Hope this helps.

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32