Search code examples
phparrayssortingmultidimensional-arraysticky

Sort rows of a 2d array with a particular "sticky" value in a column first, then sort by another column ascending


I want to sort an array by 'hits', but I also want to look for a particular ID and set that as the first iteration, then continue the 'hits' sort.

For example, I have a multidimensional array:

$myarray = [
    ["id" => 10, "hits" => 80],
    ["id" => 14, "hits" => 50],
    ["id" => 15, "hits" => 700],
    ["id" => 18, "hits" => 200],
];

I want to test whether the id is something particular, i.e. if the id==18 then put it first, then sort by hits. How would I do this, using usort and a custom function?

I think I'm looking for something similar to:

function customsort($a,$b) {
    if ($a["id"] == 18) { //or b == 18?
        return -1;
    } else {
        return $a["hits"] > $b["hits"];
    }
}

usort($myarray, "customsort");

The outcome I would like is for the order to be:

[
    ["id" => 18, "hits" => 200],
    ["id" => 14, "hits" => 50],
    ["id" => 10, "hits" => 80],
    ["id" => 15, "hits" => 700],
]

Solution

  • The only thing in your code that might make this NOT work is the return $a["hits"]>$b["hits"];. Your function should return 1/-1 only (not true/false), so change that line to: return $a["hits"]>$b["hits"]?1:-1; and it should work as expected.

    Sure enough, it works: http://codepad.org/ItyIa7fB