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');
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);