61

I have an array in this format:

Array
(
    [0] => Array
        (
            [text] => tests
            [language] => 
            [advertiserCompetitionScale] => 5
            [avgSearchVolume] => 7480000
            [lastMonthSearchVolume] => 9140000
        )

    [1] => Array
        (
            [text] => personality tests
            [language] => 
            [advertiserCompetitionScale] => 5
            [avgSearchVolume] => 165000
            [lastMonthSearchVolume] => 201000
        )

    [2] => Array
        (
            [text] => online tests
            [language] => 
            [advertiserCompetitionScale] => 5
            [avgSearchVolume] => 246000
            [lastMonthSearchVolume] => 301000
        )

)

How can I sort an array in that format, in the descending order of the avgSearchVolume field? Is there a built in function for this?

John Carter
  • 50,377
  • 25
  • 100
  • 137
Click Upvote
  • 235,452
  • 251
  • 553
  • 736

5 Answers5

110

Use usort and supply your own function to do the ordering, e.g.

function cmp($a, $b)
{
    return $b['avgSearchVolume'] - $a['avgSearchVolume'];
}

usort($array, "cmp");
hakre
  • 178,314
  • 47
  • 389
  • 754
Paul Dixon
  • 277,937
  • 48
  • 303
  • 335
18

Until PHP 5.3 this is the best function for sorting based on subkeys without making a new function for each key.

function sortBySubkey(&$array, $subkey, $sortType = SORT_ASC) {
    foreach ($array as $subarray) {
        $keys[] = $subarray[$subkey];
    }
    array_multisort($keys, $sortType, $array);
}
sortBySubkey($arr, 'avgSearchVolume');

With PHP 5.3 you can make something like this, same function call as now.

function getSortVariable($sortType = SORT_ASC) {
    switch($sortType) {
        case SORT_ASC:
            return function ($a, $b) use ($subkey) { return strcmp($a[$subkey], $b[$subkey]); };
    }
}

function sortBySubkey(&$array, $subkey, $sortType = SORT_ASC) {
    $sortFunction = getSortVariable($sortType);
    usort($array, $sortFunction($subkey));
}
OIS
  • 9,161
  • 1
  • 29
  • 41
8

You'll have to use a custom callback function together with usort().

function cmp($a, $b)
{
    if ($a['avgSearchVolume'] == $b['avgSearchVolume']) {
        return 0;
    }
    return ($a['avgSearchVolume'] > $b['avgSearchVolume']) ? -1 : 1;
}
usort($array, 'cmp');
Stefan Gehrig
  • 78,962
  • 24
  • 149
  • 181
  • While that will work, a comparison function should really return 0 if two elements being compared are equal. – Paul Dixon Apr 22 '09 at 14:58
  • You're right Paul - but as the sort-order is undefined in case of equality, a better solution would be to introduce another comparison to remove this uncertainty. Edited the answer accordingly. – Stefan Gehrig Apr 22 '09 at 15:02
2
function querySort ($first_Array,$second_Array) {
    return strcasecmp($first_Array['name'],$second_Array['name']);
}
echo '<pre>';
usort($main, 'querySort');

print_r($main);
die;
Louis B.
  • 2,179
  • 1
  • 26
  • 47
dev4092
  • 2,282
  • 1
  • 13
  • 14
1

Here is another solution, You can add multiple options for sorting(See the commented section of the code)

<?php

$arr=Array(
     Array("text" => "tests","language" =>"","advertiserCompetitionScale" => 5,"avgSearchVolume" => 7480000,"lastMonthSearchVolume" => 9140000),
     Array("text" => "personality tests","language" =>"","advertiserCompetitionScale" => 5,"avgSearchVolume" => 165000,"lastMonthSearchVolume"=>201000),
     Array("text" => "online tests","language" =>"","advertiserCompetitionScale" => 5,"avgSearchVolume" => 246000,"lastMonthSearchVolume" =>301000)
     );


$sort = array();
foreach($arr as $k=>$v) {
    $sort['avgSearchVolume'][$k] = $v['avgSearchVolume'];
    //$sort['text'][$k] = $v['text'];
}

array_multisort($sort['avgSearchVolume'], SORT_DESC, $arr);
//array_multisort($sort['avgSearchVolume'], SORT_DESC, $sort['text'], SORT_ASC,$arr);

echo "<pre>";
print_r($arr);

?>

REF: http://php.net/manual/en/function.array-multisort.php

Prasanth Bendra
  • 26,567
  • 8
  • 48
  • 67