asort

(PHP 3, PHP 4, PHP 5)

asort -- 对数组进行排序并保持索引关系

说明

bool asort ( array &array [, int sort_flags] )

本函数对数组进行排序,数组的索引保持和单元的关联。主要用于对那些单元顺序很重要的结合数组进行排序。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. asort() 例子

<?php
$fruits
= array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach (
$fruits as $key => $val) {
    echo
"$key = $val\n";
}
?>

上例将输出:

c = apple
b = banana
d = lemon
a = orange

fruits 被按照字母顺序排序,并且单元的索引关系不变。

可以用可选的参数 sort_flags 改变排序的行为,详情见 sort()

参见 arsort()rsort()ksort()sort()


add a note add a note User Contributed Notes
php at web-in-time dot com
06-Sep-2006 05:47
acecream's function works fine, especially with the spectre extension.

nevertheless sometimes the index values have to be kept. To achieve this, just replace:

$sorted_arr[] = $array[$arr_key]; 

with:

$sorted_arr[$arr_key] = $array[$arr_key];
rojaro
24-Jun-2004 10:38
Advanced sort array by second index function, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well).
Only the first two arguments are required.

<?php

function sabsi ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE) {
  if(
is_array($array) && count($array)>0) {
   foreach(
array_keys($array) as $key) $temp[$key]=$array[$key][$index];
   if(!
$natsort) ($order=='asc')? asort($temp) : arsort($temp);
   else {
     (
$case_sensitive)? natsort($temp) : natcasesort($temp);
     if(
$order!='asc') $temp=array_reverse($temp,TRUE);
   }
   foreach(
array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
   return
$sorted;
  }
  return
$array;
}

?>
csaba at alum dot mit dot edu
23-Jun-2004 07:47
If you have a pair of arrays which have a one to one association (examples: spouses, first to last name, SSN to name), when you sort one, you might wish to sort the other in the same way to maintain the correlation.  This example illustrates a way:

<?php
$aMen
= array('Fred', 'Bob', 'Tim', 'John', 'Bill');
$aPartner = array('Sue', 'Mary', 'Ann', 'Cathy', 'Nancy');
asort($aMen);                  // aMen now sorted; numeric keys out of order
$aWomen = array_keys($aMen);    // create a new array for result
foreach ($aWomen as $idx => &$name) $name=$aPartner[$name];
                              
// aWomen now has the sorted partners
$aMen = array_merge($aMen);    // put the numeric keys in order
?>

Csaba Gabor
KOmaSHOOTER at gmx dot de
21-May-2003 08:52
here another version from acecream multisorting for arrays :)

 

<?php
function array_sort_multi2($array, $key,$key2)

{
  for (
$i = 0; $i < sizeof($array); $i++) {
       if(! empty(
$array[$i][$key][$key2])){
      
$sort_values[$i] = $array[$i][$key][$key2];
       }else{
      
$sort_values[$i] = $array[$i];
       }
  }
 
asort ($sort_values);
 
reset ($sort_values);
  while (list (
$arr_keys, $arr_values) = each ($sort_values)) {
        
$sorted_arr[] = $array[$arr_keys];
  }
  return
$sorted_arr;
}
?>
spectre at hellfish dot NOSPAM dot org
29-Apr-2003 12:54
that works nicely, tho it breaks the result-array up if one or more of arrays indexes are deleted before sorting. this one should fix it up:

change:
for ($i = 0; $i < sizeof($array); $i++) {

to:
foreach ($array as $i => $k) {
acecream
23-Apr-2003 07:02
my version of sorting multi dimensional array

<?php
function array_sort($array, $key)
{
   for (
$i = 0; $i < sizeof($array); $i++) {
      
$sort_values[$i] = $array[$i][$key];
   }
  
asort ($sort_values);
  
reset ($sort_values);
   while (list (
$arr_key, $arr_val) = each ($sort_values)) {
        
$sorted_arr[] = $array[$arr_key];
   }
   return
$sorted_arr;
}
?>
mbevan at marginsoftware dot com
04-Dec-2002 05:25
Nevermind... use my last note as a quick tip: if you wish to keep the keys, use asort() and arsort() in place of sort() and rsort().
01-Aug-2002 09:48
Sorry, my last post had a typo:
// unnecessary backslashes break create_function, oops.
  if ( is_string($var) ) $var = "\'$var\'";
//it should be:
  if ( is_string($var) ) $var = "'$var'";

-- FIXED and TESTED -- :)

Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if (
is_string($var) ) $var = "'$var'";
 
uasort($x,
  
create_function('$a,$b',
    
'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return
$x;
}
?>
phzzzt .a.t. acm .d.o.t. org
01-Aug-2002 09:32
Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if (
is_string($var) ) $var = "\'$var\'";
 
uasort($x,
  
create_function('$a,$b',
    
'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return
$x;
}
?>
salchicha at cable dot net dot co
04-Apr-2002 05:23
Here's one I whipped up to allow you to sort an array of a specific class by a member or function:

<?php
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
  
$tarr = array();
  
$rarr = array();
   for(
$i = 0; $i < count($arr); $i++) {
    
$element = $arr[$i];
    
$tarr[] = strtolower($element->{$var});
   }

  
reset($tarr);
  
asort($tarr);
  
$karr = array_keys($tarr);
   for(
$i = 0; $i < count($tarr); $i++) {
    
$rarr[] = $arr[intval($karr[$i])];
   }

   return
$rarr;
}
?>

It works very well. For example, I have a Room class with members title, isActive(), date, etc. I can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and it'll work.
rcwang at cmu dot edu
03-Mar-2002 09:42
Here's my version of sorting multi-dimensional array by 2nd index.
Feel free to change the code to suit your needs.

<?php
function aSortBySecondIndex($multiArray, $secondIndex) {
   while (list(
$firstIndex, ) = each($multiArray))
      
$indexMap[$firstIndex] = $multiArray[$firstIndex][$secondIndex];
  
asort($indexMap);
   while (list(
$firstIndex, ) = each($indexMap))
       if (
is_numeric($firstIndex))
          
$sortedArray[] = $multiArray[$firstIndex];
       else
$sortedArray[$firstIndex] = $multiArray[$firstIndex];
   return
$sortedArray;
}
?>
markus at runout dot at
30-Nov-2001 04:37
for sorting CASEINSENSITIVE try
natcasesort()

there's little difference to sort,
but maybe that doesn't matter for you.
martin dot edelius at spirex dot se
29-May-2001 01:27
In the 'asortbyindex' function above there's a $ sign missing from a variable in one of the for loops:

for ($iteration = 0; $iteration < $lastiteration; iteration++)

should be:

for ($iteration = 0; $iteration < $lastiteration; $iteration++)
freeman at generalresources dot com
04-May-2001 07:51
The asortbyindex($sortarray, $index) looks like sort not asort. The key of the $sortarray was changed.
odeen at gmx dot de
30-Aug-2000 11:05
hi
the 2d arry sort works good for me,
but you should use
strtolower()
for the right alphabetical order, like this:for ($index = 0; $index < strlen ($s1); $index++) {
/**
** $s1 comes after $s2
**/

if (strtolower($s1[$index]) > strtolower($s2[$index])) return ($order);

/**
** $s1 comes before $s2
**/

if (strtolower($s1[$index]) < strtolower($s2[$index])) return (1 - $order);
}

have fun olli
sweetland at whoadammit dot com
16-Aug-2000 03:02
Here's a little routine I whipped up to sort multi-dimensional arrays:
<?php
/**
 ** comesafter ($s1, $s2)
 **
 ** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
 **/

function comesafter ($s1, $s2) {
      
/**
         ** We don't want to overstep the bounds of one of the strings and segfault,
         ** so let's see which one is shorter.
         **/

      
$order = 1;

       if (
strlen ($s1) > strlen ($s2)) {
              
$temp = $s1;
              
$s1 = $s2;
              
$s2 = $temp;
              
$order = 0;
       }

       for (
$index = 0; $index < strlen ($s1); $index++) {
              
/**
                 ** $s1 comes after $s2
                 **/

              
if ($s1[$index] > $s2[$index]) return ($order);

              
/**
                 ** $s1 comes before $s2
                 **/

              
if ($s1[$index] < $s2[$index]) return (1 - $order);
       }
 
      
/**
         ** Special case in which $s1 is a substring of $s2
         **/

      
return ($order);
}

/**
 ** asortbyindex ($sortarray, $index)
 **
 ** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
 ** of the Ith member of both the group and user arrays is a string identifier. In the
 ** case of a user array this is the username; with the group array it is the group name.
 ** asortby
 **/

function asortbyindex ($sortarray, $index) {
      
$lastindex = count ($sortarray) - 1;
       for (
$subindex = 0; $subindex < $lastindex; $subindex++) {
              
$lastiteration = $lastindex - $subindex;
               for (
$iteration = 0; $iteration < $lastiteration;    iteration++) {
                      
$nextchar = 0;
                       if (
comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index])) {
                              
$temp = $sortarray[$iteration];
                              
$sortarray[$iteration] = $sortarray[$iteration + 1];
                              
$sortarray[$iteration + 1] = $temp;
                       }
               }
       }
       return (
$sortarray);
}
?>

It's a bit long with all the comments, but I hope it helps.
bwuhlman at tallships dot ca
03-Aug-2000 06:01
Well, actually, asort has *two* annoying features.

It works perfectly well sorting hashes (or associative arrays, as you might have it), but doggedly refuses to sort regular arrays maintaining index assocation. Kind've makes sense, but the docs don't explicitly say you can't do it.

Urgggh.
jacko at kring dot co dot uk
25-Feb-2000 03:26
asort has one anoying feature, it ignores any default or implicit order in the data.  i.e. if two elements of an array contain "banana" then it is not garanteed that the first will still be the first after the sort.
This makes the Burrows-Wheeler block sort a bit of a pain to impliment, with a trailing string having to be appended to all strings before sorting, and removed after sorting. To maintain the so called "banana" order.
otterley.at.dynamine.net
14-Oct-1999 04:34
This function is the equivalent of sort values %hash in Perl.