在desc或asc中对键上的单个数组进行排序

时间:2014-09-16 09:17:10

标签: php arrays sorting ksort

有没有办法可以在desc或asc命令的特定键上对这个数组进行排序?

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

类似的东西:

ksort($array,'samaccountname','SORT_DESC');

2 个答案:

答案 0 :(得分:0)

您可以将array_multisort()用于此类事情。因为array_multisort()需要一个列数组,所以需要创建另一个数据结构进行排序。请参阅array_multisort()上的PHP文档中的示例#3。

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

答案 1 :(得分:0)

您可以使用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);