Reputation: 3125
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
Reputation: 47982
Perhaps you were overthinking this.
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
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
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