Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usort Without Replacing Keys PHP [duplicate]

Tags:

arrays

php

usort

I am having MAJOR usort() issues! :( So basically I want to sort my array by their values. I would like the values to display in this order: Platinum, Gold, Silver, Bronze, Complete, None, Uncomplete. Now I can sort them well, but I would like to preserve their key (is that possible?). here is my code:

function compareMedals( $a, $b ) {
    $aMap = array(1 => 'Platinum', 2 => 'Gold', 3 => 'Silver', 4 => 'Bronze', 5 => 'Complete', 6 => 'None', 7 => 'Uncomplete');
    $aValues = array( 1, 2, 3, 4, 5, 6, 7);
    $a = str_ireplace($aMap, $aValues, $a);
    $b = str_ireplace($aMap, $aValues, $b);
    return $a - $b;
}
usort($list, 'compareMedals');

So is it possible to sort them WHILE preserving their keys? Thank You! :)

EDIT

Array:

$array = array("post1" => 'Platinum', "Post2" => "Bronze, "Post3" = > Gold)

Should output:

"Post1" => 'Platinum',
"Post3" => 'Gold',
"Post2" => 'Bronze'

Yet it is outputting this:

"0" => 'Platinum',
"1" => 'Gold',
"2" => 'Bronze'
like image 735
michael jones Avatar asked Dec 06 '25 02:12

michael jones


2 Answers

Just use uasort intead of usort. Definition of uasort is

Sort an array with a user-defined comparison function and maintain index association.

There is an example of code with your comparing function and uasort:

$list = array('post1' => 'Gold', 'post2' => 'None', 'post3' => 'Platinum');

function compareMedals( $a, $b ) {
    $aMap = array(1 => 'Platinum', 2 => 'Gold', 3 => 'Silver', 4 => 'Bronze', 5 => 'Complete', 6 => 'None', 7 => 'Uncomplete');
    $aValues = array( 1, 2, 3, 4, 5, 6, 7);
    $a = str_ireplace($aMap, $aValues, $a);
    $b = str_ireplace($aMap, $aValues, $b);
    return $a - $b;
}
uasort($list, 'compareMedals');

print_r($list);

That code gives result

Array
(
    [post3] => Platinum
    [post1] => Gold
    [post2] => None
)
like image 194
SeriousDron Avatar answered Dec 08 '25 15:12

SeriousDron


usort did not preserve the key, if you want to preserve key after sort then you should use asort. Hope this help you.

like image 39
Vijay Verma Avatar answered Dec 08 '25 15:12

Vijay Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!