0

Is there a way i can sort this array on a specific key in desc or asc order?

<?php 
$array = array(
   "samaccountname" => "Mark", => "age" => "26", 
   "samaccountname" => "John", => "age" => "50", 
   "samaccountname" => "Peter", => "age" => "31", 
   "samaccountname" => "Dennis", "age" => "21"
); 
?>

Something like:

ksort($array,'samaccountname','SORT_DESC');
helloflash
  • 2,424
  • 2
  • 12
  • 19
  • 1
    In other news, your array definition is broken, you can't have multiple `=>` operators in a single array key definition – Joe Sep 16 '14 at 09:35

2 Answers2

0

You may use array_multisort() for that sort of thing. Because array_multisort() requires an array of columns you need to create another data structure for sorting, though. See example #3 in the PHP documentation on array_multisort().

$myarr = array(
  array("samaccountname" => "Mark", "age" => "26"), 
  array("samaccountname" => "John", "age" => "50"), 
  array("samaccountname" => "Peter", "age" => "31"), 
  array("samaccountname" => "Dennis", "age" => "21")); 

foreach ($myarr as $key => $row) {
       $samaccountname[$key] = $row['samaccountname'];
       $age[$key] = $row['age'];
}

array_multisort($samaccountname, SORT_DESC, $myarr);
var_dump($myarr);
ofrommel
  • 1,795
  • 10
  • 15
0

You can use usort to write a custom sort function. This way you can sort by a specific key of the sub-arrays of the array to sort. You can even wrap this in your own function:

<?php
// Fixed syntax of your nested array:
$array = array(
   array("samaccountname" => "Mark", "age" => "26"), 
   array("samaccountname" => "John", "age" => "50"), 
   array("samaccountname" => "Peter", "age" => "31"), 
   array("samaccountname" => "Dennis", "age" => "21")
); 

/**
 * Sorts a nested array by the value of the specified key. Can sort ascending or descending */
 */
function myksort(&$array, $subkey, $sort = SORT_ASC)
{
    return usort($array,
        // The callback function. Make sure it can use $subkey and $sort.
        function($a, $b) use ($subkey, $sort) {
            // Compare the items respecting the sort.
            if ($sort == SORT_DESC)
              return strcmp($b[$subkey], $a[$subkey]);
            else
              return strcmp($a[$subkey], $b[$subkey]);
        });
}

// Sort the array by 'samaccountname'
myksort($array, 'samaccountname');

// Show the results.
var_dump($array);

// Sort the array by 'samaccountname', but descending.
myksort($array, 'samaccountname', SORT_DESC);

// Show the results.
var_dump($array);

The compare function itself can be shorter as well, if you write it like this, but I think the if..else is a little more readable.

return strcmp($a[$subkey], $b[$subkey]) * ($sort == SORT_DESC?-1,1);
GolezTrol
  • 109,399
  • 12
  • 170
  • 196