user1899415
user1899415

Reputation: 3125

PHP: assign priority to array values and then sort by that priority

Is there a way to assign a "priority score" to an array in PHP? Then sort based on that priority. Given my input:

Array(
  [princeton] => Princeton
  [stanford] => Stanford
  [yale] => Yale
  [mit] => MIT
  [harvard] => Harvard 
)

I would like the output to always have Harvard and Yale at the top, the rest alphabetically sorted:

Array(
  [harvard] => Harvard
  [yale] => Yale
  [mit] => MIT
  [princeton] => Princeton
  [stanford] => Stanford    
)

I checked out asort() which does the alphabetical and uasort() which is custom-defined, but I'm stuck on how I can "assign a priority". Any help would be appreciated!

Upvotes: 0

Views: 1698

Answers (3)

mickmackusa
mickmackusa

Reputation: 47982

Perhaps you were overthinking this.

  1. sort by key
  2. replace your short priority array with the alphabetized array

Code: (Demo)

$ivyLeaguers = [
  'princeton' => 'Princeton',
  'cornell' => 'Cornell',
  'stanford' => 'Stanford',
  'yale' => 'Yale',
  'mit' => 'MIT',
  'harvard' => 'Harvard'
];

ksort($ivyLeaguers);
var_export(
    array_replace(['harvard' => null, 'yale' => null], $ivyLeaguers)
);

Output:

array (
  'harvard' => 'Harvard',
  'yale' => 'Yale',
  'cornell' => 'Cornell',
  'mit' => 'MIT',
  'princeton' => 'Princeton',
  'stanford' => 'Stanford',
)

The null values are overwritten but their position is respected. This technique pulls the priority schools to the top of the list based on the matching keys.

Upvotes: 1

anthonygore
anthonygore

Reputation: 4977

uasort will sort your array by your own comparison function. I've made the function place either Harvard or Yale first (the ordering of those two will be uncertain since you haven't specified) and sort the rest alphabetically.

function cmp($a, $b) {
    if ($a == 'Yale' || $a == 'Harvard') {
        return -1;
    } else if ($b == 'Yale' || $b == 'Harvard') {
        return 1;
    } else return strcmp($a, $b);
}

uasort($array, 'cmp');

Upvotes: 2

Eugen Rieck
Eugen Rieck

Reputation: 65294

Assuming you have something like

$priotities=array(
  [harvard] => 1
  [yale] => 2
  [mit] => 3
  [princeton] => 4
  [stanford] => 5
)

you could

$final=$priorites;
sort(final);
foreach ($final as $k=>$v) 
  $final[$k]=$universities[$k];

Upvotes: 0

Related Questions