I have an array that looks something like this:
Array
(
    [Erik] => Array
    ( 
        [count] => 10
        [changes] => 1
    )
    [Morten] => Array
    (
        [count] => 8
        [changes] => 1
    )
)
Now, the keys in the array are names of technicians in our Helpdesk-system. I'm trying to sort this based on number of [count] plus [changes] and then show them. I've tried to use usort, but then the array keys are replaced by index numbers. How can I sort this and keep the array keys?
PHP - Sort Functions For Arraysrsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key. arsort() - sort associative arrays in descending order, according to the value.
Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.
The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.
php function sortArray() { $inputArray = array(8, 2, 7, 4, 5); $outArray = array(); for($x=1; $x<=100; $x++) { if (in_array($x, $inputArray)) { array_push($outArray, $x); } } return $outArray; } $sortArray = sortArray(); foreach ($sortArray as $value) { echo $value . "<br />"; } ?>
Try using uasort():
<?
function cmp($a, $b)
{
   return ($b['count'] + $b['changes']) - ($a['count'] + $a['changes']);
}
$arr = array(
   'John' => array('count' => 10, 'changes' => 1),
   'Martin' => array('count' => 5, 'changes' => 5),
   'Bob' => array('count' => 15, 'changes' => 5),
);
uasort($arr, "cmp");
print_r($arr);
?>
prints:
Array
(
   [Bob] => Array
   (
      [count] => 15
      [changes] => 5
   )
   [John] => Array
   (
      [count] => 10
      [changes] => 1
   )
   [Martin] => Array
   (
      [count] => 5
      [changes] => 5
   )
)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With