您可以使用usort 编写自定义排序函数。这样就可以通过对数组的子数组的特定键进行排序。您甚至可以将其包装在您自己的函数中:
<?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);
比较函数本身也可以更短,如果你这样写的话,但我认为if..else 更具可读性。
return strcmp($a[$subkey], $b[$subkey]) * ($sort == SORT_DESC?-1,1);