0
array(4) {
    [LAA] = array(2) {
        [games] = int() 81
        [total] = int() 2135199
    }
    [TOA] = array(2) {
        [games] = int() 4
        [total] = int() 54957
    }
    [KCA] = array(2) {
        [games] = int() 3
        [total] = int() 36510
    }
    [HOA] = array(2) {
        [games] = int() 10
        [total] = int() 363482
    }

I wish to have a specific key (3-char team abbreviation, e.g. LAA) always be on top after a sort. I have successfully done this with SQL, as follows:

$team = "LAA";

ORDER BY CASE WHEN team = '$team' THEN 1 ELSE 2 END, team

But would like to do it with a PHP sort when a database is not available.

ksort orders by keys: HOA, KCA, LAA, TOA.

What I want is to pick a key, say LAA, and ensure it's first in the order, with the rest of the keys sorted after LAA. Result to be: LAA, HOA, KCA, TOA.

I have not found solution on stackoverflow.

Update. I wrote the following and it works. Sort the array (can do either sort or rsort), iterate through the array finding the one element I wish to place on top, save it, finish rest of iteration, then merge the saved element with the array.

function my_ksortD(&$arg, $team) {  // sorting the keys separately (rsort descending) and then deleting the elements 
                                    // one-by-one and appending them to the end, in descending order.
                                    // This will take $team key and place it at the top of array.
    $keys=array_keys($arg);
    rsort($keys);
    foreach($keys as $key) {
        $val=$arg[$key];
        unset($arg[$key]);
        if($key == $team) {
            $saveVal[$key] = $val;
        }
        else {
            $arg[$key]=$val;
        }
    }
    $arg = array_merge($saveVal, $arg);
}
``
user2140857
  • 129
  • 12
  • I think you need a secondary key or lookup to sort by (as you effectively did in the sql). Otherwise it's a completely arbitrary order. – ADyson Jan 25 '23 at 17:35
  • 1
    What you think about using usort with an anonymous function? – Valeriy Tito Jan 25 '23 at 17:50
  • _"I've seen many key sort examples but nothing for what I'm looking to do."_ - what you do with uksort, is provide a callback function that "compares" two keys it gets passed in, to determine which one should come first. So all you have to do is check whether either of them is `LAA` - in that case, this item is coming first no matter what, so you return -1 or 1 accordingly. And if not, then you compare the two keys you got, which one of those is _actually_ "lesser", and return the appropriate value based on that. – CBroe Jan 26 '23 at 10:09

0 Answers0