1

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 = array(
    array(
        "id"=>10,
        "hits"=>80
    ),
    array(
        "id"=>14,
        "hits"=>50
    ),
    array(
        "id"=>15,
        "hits"=>700
    ),
    array(
        "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 :

array(
    "id"=>18,
    "hits"=>200
),
array(
    "id"=>14,
    "hits"=>50
),
array(
    "id"=>10,
    "hits"=>80
),
array(
    "id"=>15,
    "hits"=>700
)

(or if they were labelled ABCD then I need it to be DBAC)

Tim
  • 6,986
  • 8
  • 38
  • 57
  • possible duplicate of [PHP - Multiple uasort functions breaks sorting](http://stackoverflow.com/questions/5198276/php-multiple-uasort-functions-breaks-sorting) – Jon Jul 02 '12 at 08:40
  • Duplicate of lots of questions really, but the one above has a turnkey solution (I know because it's mine). – Jon Jul 02 '12 at 08:41
  • so you just need to change $a["hits"]>$b["hits"]; to return $a["hits"]>$b["hits"]; – Waygood Jul 02 '12 at 08:43
  • I dont want to sort by ID then Hits, I want to look for one particular ID then order the rest by Hits... if that makes sense. – Tim Jul 02 '12 at 08:47
  • Seems like a simple case of writing a custom comparator? – Corbin Jul 02 '12 at 08:49

1 Answers1

1

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

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
  • Oh awesome!! Thanks! Don't I have to also compare $b["id"] though where I've put the comment? – Tim Jul 02 '12 at 08:55