Search code examples
phparrayssortingmultidimensional-array

Sort a 2d array by a column descending


I have a script which gets some values from a DB.

The structure of the vars is as the following:

$dump["likes"] = 1234;
$likes["data"][$i]["name"] = "ABCDEFG";

for ($i=0;$i<=$max;$i++) {
    $data[$i]["likes"] = $dump["likes"];
    $data[$i]["name"] = $likes["data"][$i]["name"];
}

//Print sorted array here (highest value in "like" first)

I just need a way to find out in which entry the biggest "likes" are :)

I have tried array_multisort(), but it showed me "inconsistent size" or some error...

EDIT:

When I print($data) outside of the end loop it looks like this:

Array (
    [0] => Array ( [likes] => 3485109 [name] => Google )
    [1] => Array ( [likes] => 78535 [name] => Youtube )
    [2] => Array ( [likes] => 2433041 [name] => Bing )
)

I would like to have an array like this:

Array (
    [0] => Array ( [likes] => 3485109 [name] => Google )
    [1] => Array ( [likes] => 2433041 [name] => Bing )
    [2] => Array ( [likes] => 78535 [name] => Youtube )
)
//Sorted by "likes"

Solution

  • This should do the trick

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