Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting PHP array using subkey-values

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?

like image 222
eriktm Avatar asked Jul 04 '11 10:07

eriktm


People also ask

How do you sort an array by a specific value in PHP?

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.

How do I sort a multi dimensional array in PHP?

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.

How do you sort an associative array in PHP?

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.

How can we sort an array without using sort method in PHP?

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 />"; } ?>


1 Answers

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
   )
)
like image 75
johnhaggkvist Avatar answered Sep 29 '22 23:09

johnhaggkvist