Jetro Bernardo
Jetro Bernardo

Reputation: 67

sort an array by key and by value too in PHP

How to sort an array by ascending key and descending value? enter image description here

Upvotes: 0

Views: 93

Answers (3)

Jetro Bernardo
Jetro Bernardo

Reputation: 67

This problem has been solved in Stack in Portuguese, in the following link: https://pt.stackoverflow.com/questions/361111/como-classificar-array-pela-chave-e-pelo-valor-sem-perder-o-valor-original-da-c#361115

Upvotes: 0

Adarsh Sojitra
Adarsh Sojitra

Reputation: 2219

Here is the code you are looking for.

<?php
$array = array(5=>100,4=>100,3=>100,1=>100,8=>97,6=>97,9=>82,7=>80);

$keys = array_keys($array);
$values = array_values($array);

sort($keys);
rsort($values);
for($i=0;$i<=count($keys)-1;$i++){
    $array[$keys[$i]] = $values[$i];
}
?>

Upvotes: 0

TsV
TsV

Reputation: 639

    array_multisort(array_values($array), SORT_DESC, array_keys($array), SORT_ASC, $array);

Upvotes: 1

Related Questions