0

I have this array :

$myarray
(
    [5] => Array
        (
            [count] => 2
            [aaa] => 119
        )

    [2] => Array
        (
            [count] => 5
            [aaa] => 90
        )

    [3] => Array
        (
            [count] => 7
            [aaa] => 91
        )

    [4] => Array
        (
            [count] => 12
            [aaa] => 119
        )

    [1] => Array
        (
            [count] => 8
            [aaa] => 119
        )
)

I want sort this array by the "count" value for get the three id (the key) that have the biggest counter.

With my exemple :

print_r(customfunction($myarray))
// display : array(4,1,3)

Because [4] have count = 12, [4] have count = 8, and [4] have count = 7. How can I sort my array ? and get the three id that have the biggest counster ?

Thank you =)

spacecodeur
  • 2,206
  • 7
  • 35
  • 71
  • 1
    http://php.net/manual/en/array.sorting.php – Kaylined Sep 09 '16 at 23:11
  • Possible duplicate of [PHP sort array by key](http://stackoverflow.com/questions/27691470/php-sort-array-by-key) – Red Mercury Sep 10 '16 at 00:09
  • 1
    What have you tried? You should add some actual sorting code, if you have tried. – segFault Sep 10 '16 at 00:13
  • 1. [`usort()`](http://php.net/manual/en/function.sort.php), [`uasort()`](http://php.net/manual/en/function.uasort.php) if you need to preserve your array indexes. 2. [`array_slice()`](http://php.net/manual/en/function.array-slice.php), maybe preceded with [`array_keys()`](http://php.net/manual/en/function.array-keys.php) if you're only interested in the indexes. – Sammitch Sep 10 '16 at 00:54

1 Answers1

0

Thanks all for usefull links :)

This is the solution !

function cmp($a, $b){
  if ($a['count'] > $b['count']){
    return -1;
  } elseif($a['count'] < $b['count']){
    return 1;
  } else return 0;
}

...

uasort($myarray, "cmp");
spacecodeur
  • 2,206
  • 7
  • 35
  • 71