数组 函数
在线手册:中文  英文

asort

(PHP 4, PHP 5)

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

说明

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

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

参数

array

输入的数组。

sort_flags

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

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

Example #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 被按照字母顺序排序,并且单元的索引关系不变。

参见


数组 函数
在线手册:中文  英文

用户评论:

stephen [ at ] brooksie-net [ dot ] co [ dot ] uk (2013-03-01 16:37:05)

It is obviously necessary to log the keys used as so we don't overwrite previous entries in the array ;o)

N.B. this also effects the timings, but still faster than the alternatives : 

     * int : 0.00159    (ms)
     * str : 0.00092    (ms)

<?php
private function _keySort(Array $data
    {
        
$keys = array();
        
        foreach(
$data as $row) {
            
            
$keyIncrement 
                (!isset(
$keys[$row[$this->_orderField]])) 
                    ? 
$keys[$row[$this->_orderField]] = 0
                    
: ++$keys[$row[$this->_orderField]];

            
$tempArray[$row[$this->_orderField].$keyIncrement] = $row;
        }

        if (
$this->_orderDirection == 'DESC') {
            
krsort($tempArraySORT_NATURAL SORT_FLAG_CASE );
        } else {
            
ksort($tempArraySORT_NATURAL SORT_FLAG_CASE);
        }

        return 
$tempArray;           
            
    }
?>

nick ([AT]) nickyost ([DOT]) com (2011-09-15 15:32:58)

This function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     
// Sort the multidimensional array
     
usort($results"custom_sort");
     
// Define the custom sort function
     
function custom_sort($a,$b) {
          return 
$a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution.

Hope it helps!

Anon (2011-05-06 17:37:49)

Case insensitive sort in one line:

<?php

array_multisort
(array_map('strtolower'$array), $array);

?>

rick at toewsweb dot net (2011-04-28 16:40:22)

On sorting by value first, then by key (cf., 2008-01-31 notes by mike at clear-link dot com):

What occurred to me to solve this problem was to extract the keys and values into separate arrays, then use array_multisort to get the desired order:

Ex:
<?php
$kvpairs 
= array('noun' => 'thought''animal' => 'fish''abstract' => 'thought''food' => 'fish''verb' => 'fish');
print 
"before:\n";
print_r($kvpairs);

// Essentially, one line of code is all that's needed for the sort:
array_multisort(array_values($kvpairs), array_keys($kvpairs), $kvpairs);

print 
"after:\n";
print_r($kvpairs);
?>

before:
Array
(
    [noun] => thought
    [animal] => fish
    [abstract] => thought
    [food] => fish
    [verb] => fish
)
after:
Array
(
    [animal] => fish
    [food] => fish
    [verb] => fish
    [abstract] => thought
    [noun] => thought
)

Of course, array_multisort allows you to specify sort order (SORT_ASC, SORT_DESC) and sort type (SORT_REGULAR, SORT_STRING, SORT_NUMERIC) for each array you pass it.

ebade at yahoo dot com (2009-07-09 13:30:29)

<?php
// Sort an associative array while case insensitive
// Might be useful to someone else
// 
// Example:
// $arr = $res1 = array(
//              [a] => Trans Union
//              [b] => TRACE
//              [c] => TeleMatch
//              [d] => test);
//
// asort($res1);
// $res2 = asorti($arr);
//
// ASORT RESULT
// $res1 = array(
//              [b] => TRACE
//              [c] => TeleMatch
//              [a] => Trans Union
//              [d] => test);
//
// DESIRED RESULT
// $res2 = array(
//              [c] => TeleMatch
//              [d] => test
//              [b] => TRACE
//              [a] => Trans Union);

function asorti($arr) {
   
$arr2 $arr;
   foreach(
$arr2 as $key => $val) {
      
$arr2[$key] = strtolower($val);
   }
 
   
asort($arr2);
   foreach(
$arr2 as $key => $val) {
      
$arr2[$key] = $arr[$key];
   }

   return 
$arr2;
}
?>

Eran (2009-04-21 17:15:23)

i made this sample multi dimensional array sort to someone who needed to read lines from a text file instead of using sql - order by statement.

the idea is to take the key and sort(order) the specific column and then order the entire of the array as the selected column asort returned.

<?php
/**
 * 
 * This sample is reading text data
 * and perform a sort to a 2 dimensional array
 * just like a normal sql do to "order by asc" 
 * 
 */

$foo = array();

/*
# SORT_REGULAR - compare items normally (don't change types)
# SORT_NUMERIC - compare items numerically
# SORT_STRING - compare items as strings
*/
$sort_by SORT_REGULAR;

/*
# 0 - order by name column
# 1 - order by age column
# 2 - order by rank column
# 3 - order by color column
*/
$order_by 1;

// source file
$line_of_text[1] = 'a1name|f2age|h3rank|jcolor';
$line_of_text[2] = 'b1name|d2age|i3rank|k4color';
$line_of_text[0] = 'c1name|e2age|g3rank|l4color';

// make array
for ($x=0$x<=2$x++)
{
    
$line explode('|',$line_of_text[$x]);

    
// save it by coulmns otherwise it will saved like rows
    
for ($i=0$i<=3$i++) {
          
$foo[$i][$x] = $line[$i];
    }
}

// get the key order
$a $foo[$order_by];

// sort
asort($a$sort_by);

// start print
echo "<table cellpudding=0 cellspacing=0 border=1>\n";
        echo 
"<tr>\n";
          echo 
"<td>key</td>\n";
          echo 
"<td>name</td>\n";
          echo 
"<td>age</td>\n";
          echo 
"<td>rank</td>\n";
          echo 
"<td>color</td>\n";
        echo 
"</tr>\n";

// print by key order
foreach ($a as $k => $v) {
    echo 
"<tr>\n";
      echo 
"<td>$k</td>\n";
      
// you can print here a for loop (0 to num of columns[=3])
      
echo "<td>".$foo[0][$k]."</td>\n";
      echo 
"<td>".$foo[1][$k]."</td>\n";
      echo 
"<td>".$foo[2][$k]."</td>\n";
      echo 
"<td>".$foo[3][$k]."</td>\n";
    echo 
"</tr>\n";
}
echo 
"</table>\n";
?>

Cai Black (2009-03-05 11:20:13)

I could not find a built-in to handle this specific case.  I hope that someone else finds it useful as well.

<?php
// array_sort_numerically_indexed_values
//
// (PHP 4, PHP 5)
//
// array_sort_numerically_indexed_values - Sort the numerically indexed values of an array.
//
//
// Description:
//
//   bool array_sort_numerically_indexed_values ( array &$array )
//
//   This function sorts the only values of the array that are numerically indexed.  This is mainly useful when sorting values that were returned from a datasource where value ordering is not specified, is not configurable, or is unknown.
//
//
// Parameters:
//
//   array
//     The input array.
//
// Return Values:
//
//   Returns TRUE on success or FALSE on failure (see below for more information).
//
//
// Notes:
//
//   The input array MUST contain an element 'count' with an integer value representing the number of numerically indexed array elements.
//
//
// Examples:
//
//   Example #1 array_sort_numerically_indexed_values example
//
//     <?php
//     // An array wherein the numerically indexed elements ($pets[0] through $pets[3]) are unordered.
//     $pets=array(
//       0 => 'Biscuit',
//       1 => 'Alley',
//       2 => 'Doogie',
//       3 => 'Conan',
//       'Conan' => array(
//         0 => 'cat',
//         1 => 'male'
//       ),
//       'Biscuit' => array(
//         0 => 'cat',
//         1 => 'female'
//       ),
//       'Doogie' => array(
//         0 => 'dog',
//         1 => 'male'
//       ),
//       'Alley' => array(
//         0 => 'dog',
//         1 => 'female'
//       ),
//       'count' => 4
//     );
//     
//     array_sort_numerically_indexed_values($pets);
//     
//     print_r($pets);
//     
?>
//
//     The above example will output:
//
//       Array
//         (
//           [0] => Alley
//           [1] => Biscuit
//           [2] => Conan
//           [3] => Doogie
//           [Conan] => Array
//             (
//               [0] => cat
//               [1] => male
//             )
//           [Biscuit] => Array
//             (
//               [0] => cat
//               [1] => female
//             )
//           [Doogie] => Array
//             (
//               [0] => dog
//               [1] => male
//             )
//           [Alley] => Array
//             (
//               [0] => dog
//               [1] => female
//             )
//           [count] => 4
//         )
//
//     The numerically index array elements were sorted alphabetically.
//
// Credits:
//   Cai Black < caiblack [at] hotmail [dot] com >
//

function array_sort_numerically_indexed_values(&$myArray) {
    if(isset($myArray['count'])) {
        $sort_again=true;
        if( $sort_again && ($myArray['count'] > 1) ) {
            $sort_previous_value='';
            for($i=0; $i<$myArray['count']; $i++) {
                $sort_again=false;
                // if not the first item then
                if($i > 0) {
                    // if current index value is less than previous value then
                    if($myArray[$i] < $myArray[$i-1]) {
                        // set swap to current index value
                        $sort_swap=$myArray[$i];
                        // set current index to previous index value
                        $myArray[$i]=$myArray[$i-1];
                        // set previous index to swap value
                        $myArray[$i-1]=$sort_swap;
                        // set $sort_again to true
                        $sort_again=true;
                    } // end if
                } // end if
                // set $sort_previous_value to current index value
                $sort_previous_value=$myArray[$i];
            } // end for
        } // end if
        return true;
    } else {
        return false;
    } // end if
} // end function array_sort_numerically_indexed_values
?>

ThA-B (2008-10-11 05:11:13)

mzvarik at gmail dot com!
Your post at 16-Jan-2008 12:46 saved my life, so I request it not to be deleted, but put somewhere in more visible place.
I got situation, where server is not (and will not be) configured properly and latvian language can not be recognized neither in setlocale or sort functions.
Latvian is also known as ISO-8859-13, lv_LV, lv, lv_LV.ISO-8859-13, cp1257, windows-1257, etc. And because non of them worked with setlocale() and sort() under win32/php5.2.1 environment, i used your functions MySort() and myStrCmp() with slight change:
$cz_chars = 'Aa ?ā Bb Cc ?? Dd Ee ?ē Ff Gg ?? Hh Ii ?ī Jj Kk ?? Ll ?? Mm Nn ?? Oo Pp Rr Ss ?? Tt Uu ?ū Vv Zz ??';
voila!
Thank You very very much!

bakatamas at freemail dot hu (2008-02-15 14:34:59)

Dear mike at clear-link dot com!
I needed a case insensitive version of your function. It is still not perfect as I have to do something with country specific characters (?üó?úéá?í?????????)
function akisort(&$array,$valrev=false,$keyrev=false)
{
if ($valrev)
{
arsort($array);
}
else
{
asort($array);
};
$vals = array_count_values($array);
$i = 0;
foreach ($vals AS $val=>$num)
{
$first = array_splice($array,0,$i);
$tmp = array_splice($array,0,$num);
$tmp2 = array();
foreach($tmp as $key => $value)
{
$tmp2[] = $key;
$number = $value;
};
natcasesort($tmp2);
reset($tmp2);
print_r($tmp2);
unset($tmp);
foreach($tmp2 as $key => $value)
{
$tmp[$value] = $number;
};
if($keyrev)
{
$tmp = array_reverse($tmp, true);
};
$array = array_merge($first,$tmp,$array);
unset($tmp);
$i = $i+$num;
};
};

mike at clear-link dot com (2008-01-31 15:56:00)

Small typo in the aksort function I just submitted. Here's the entire thing again, with the correction noted:

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if (
$valrev) { arsort($array); } else { asort($array); }
  
$vals array_count_values($array);
    
$i 0;
    foreach (
$vals AS $val=>$num) {
        
$first array_splice($array,0,$i);
        
$tmp array_splice($array,0,$num);
        if (
$keyrev) { krsort($tmp); } else { ksort($tmp); }
        
$array array_merge($first,$tmp,$array);
        unset(
$tmp);
        
$i $i+$num;
        
// Fixed from previous post: $i = $num;
    
}
}
?>

mike at clear-link dot com (2008-01-31 15:23:55)

For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if (
$valrev) { arsort($array); } else { asort($array); }
    
$vals array_count_values($array);
    
$i 0;
    foreach (
$vals AS $val=>$num) {
        
$first array_splice($array,0,$i);
        
$tmp array_splice($array,0,$num);
        if (
$keyrev) { krsort($tmp); } else { ksort($tmp); }
        
$array array_merge($first,$tmp,$array);
        unset(
$tmp);
        
$i $num;
    }
}

// Example
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);

// Standard asort
asort($tmp);
print_r($tmp);

// Sort value ASC, key ASC
aksort($tmp);
print_r($tmp);

// Sort value DESC, key ASC
aksort($tmp,true);
print_r($tmp);

// Sort value DESC, key DESC
aksort($tmp,true,true);
print_r($tmp);

// Results
Array
(
    [
pe] => 1
    
[ca] => 1
    
[ce] => 1
    
[cb] => 2
    
[pa] => 2
)
Array
(
    [
ca] => 1
    
[ce] => 1
    
[pe] => 1
    
[cb] => 2
    
[pa] => 2
)
Array
(
    [
cb] => 2
    
[pa] => 2
    
[ca] => 1
    
[ce] => 1
    
[pe] => 1
)
Array
(
    [
pa] => 2
    
[cb] => 2
    
[pe] => 1
    
[ce] => 1
    
[ca] => 1
)

mzvarik at gmail dot com (2008-01-16 09:29:53)

I noticed that my function mentioned earlier is very misleading - somebody please delete that note!

This is how you sort:
<?php
setlocale 
(LC_ALL'czech');
$array = array("a""?""c");
usort ($array'strcoll');
print_r($array);
?>

przemekkus [at] interia [dot] pl (2007-11-02 06:34:50)

Function written by a dot brandon at chello dot nl has an error - wrong variable name. It should be:
if($rev) arsort($named_hash,$flags=0) ;
instead of
if($reverse) arsort($named_hash,$flags=0) ;

greenie2600 at yahoo dot com (2007-08-09 12:22:25)

The function offered by richard at happymango dot me dot uk does not handle numeric indices properly. smileaf's suggested fix did not work for me. Use with caution.

a dot brandon at chello dot nl (2007-06-25 19:18:50)

I use this for quasi-SQL orderby. Loosely based on smileaf. Any good for you nerds?

<?

function named_records_sort($named_recs, $order_by, $rev=false, $flags=0)
{// Create 1-dimensional named array with just 
 // sortfield (in stead of record) values
    $named_hash = array(); 
     foreach($named_recs as $key=>$fields) 
             $named_hash["$key"] = $fields[$order_by];
 
 // Order 1-dimensional array, 
 // maintaining key-value relations   
    if($reverse) arsort($named_hash,$flags=0) ;
    else asort($named_hash, $flags=0);
  
 // Create copy of named records array 
 // in order of sortarray  
    $sorted_records = array(); 
    foreach($named_hash as $key=>$val) 
           $sorted_records["$key"]= $named_recs[$key];
  
return $sorted_records;} // named_recs_sort()

function show_sorted_records($named_recs, $order_by, $rev=false, $flags=0)
{$sorted_records=named_records_sort($named_recs, $order_by, $rev, $flags);
foreach($sorted_records as $name=>$fields) 
  {echo "<b>$name</b>   "; 
   foreach($fields as $field=>$val) 
          echo "$field = $val "; echo "<br>";}
} // show_sorted_records()

$girl_friends=array();
$girl_friends["Anna"]=
array("born"=>'1989-08-22',"cupsize"=>'B-',"IQ"=>105, "daddy"=>'rich');
$girl_friends["Zoe"]
=array("born"=>'1978-03-11',"cupsize"=>'C#',"IQ"=>130, "daddy"=>'poor');
$girl_friends["Lilly"]
=array("born"=>'1985-06-16',"cupsize"=>'DD',"IQ"=>90, "daddy"=>'nasty');

$order_by="cupsize"; echo "And the winners are: <br>";
show_sorted_records($girl_friends, $order_by, true);

?>

gunnar at taljaren dot se (2007-06-14 01:00:24)

for ($i=0;$i<5;$i++)
$values[] = $i;
asort($values);
works, but
for ($i=0;$i<5;$i++)
$values[$i] =$i;
asort($values);
doesn't!

nilesh dot gamit at gmail dot com (2007-04-25 03:50:58)

function to sort 2d array: recordSort(); It is really helpful as most PHP sort functions provides facility for sorting 1d array & multi dimensional array sorting is not handy. Normally this function will help u.. if u r displaying some records n u want sorting by clicking on some column. basically same is achieved by direct SQL changes like ORDER BY ASC/DESC. But in case, if your records are not actual records, this function will help. i.e. some table has following fields in DB. 
name, email, telephone and are_you_married; are_you_married is either 0 / 1. now u r displaying N for 1 and Y for 0; and you want sorting on are_you_married on display. then ORDER BY ASC/DESC. will not work. So, try this…

<?php
    
function recordSort($records$field$reverse$defaultSortField 0)
    {
            
$uniqueSortId 0;
            
$hash = array(); $sortedRecords = array(); $tempArr = array(); $indexedArray = array(); $recordArray = array();

            foreach(
$records as $record) {
                
$uniqueSortId++;
                
$recordStr implode("|"$record)."|".$uniqueSortId;
                
$recordArray[] = explode("|"$recordStr);
            }

            
$primarySortIndex count($record);
            
$records $recordArray;

             foreach(
$records as $record) {
                
$hash[$record[$primarySortIndex]] = $record[$field];
             }
            
uasort($hash"strnatcasecmp");
            if(
$reverse)
            
$hash array_reverse($hashtrue);

            
$valueCount array_count_values($hash);

            foreach(
$hash as $primaryKey => $value) {
                
$indexedArray[] = $primaryKey;
            }          

            
$i 0;
            foreach(
$hash as $primaryKey => $value) {
                
$i++;
                if(
$valueCount[$value] > 1) {
                    foreach(
$records as $record)  {
                        if(
$primaryKey == $record[$primarySortIndex]) {
                            
$tempArr[$record[$defaultSortField]."__".$i] = $record;
                            break;
                        }
                    }

                    
$index array_search($primaryKey$indexedArray);

                    if( (
$i == count($records)) || ($value != $hash[$indexedArray[$index+1]]) )  {
                        
uksort($tempArr"strnatcasecmp");

                        if(
$reverse)
                        
$tempArr array_reverse($tempArr);

                        foreach(
$tempArr as $newRecs) {
                            
$sortedRecords [] = $newRecs;
                        }

                        
$tempArr = array();
                    }
                }
                else {
                    foreach(
$records as $record)  {
                       if(
$primaryKey == $record[$primarySortIndex])  {
                                
$sortedRecords[] = $record;
                                break;
                        }
                    }
                }
            }
            return 
$sortedRecords;
    }

    
$array[0][0] = 'nilesh';   // sort_index = 0
    
$array[0][1] = 'yogesh'// sort_index = 1
    
$array[0][2] = 'aakash'// sort_index = 2
    
$array[0][3] = '100';      // sort_index = 3
    
$array[0][4] = 'nilesh';   // sort_index = 4
    
$array[0][5] = 'Nil100';  // sort_index = 5
    
$array[0][6] = 'Y';         // sort_index = 6

    
$array[1][0] = 'Nil100';
    
$array[1][1] = '1001';
    
$array[1][2] = 'nilesh';
    
$array[1][3] = 'nilesh';
    
$array[1][4] = 'nilesh';
    
$array[1][5] = 'yogesh';
    
$array[1][6] = 'Nil100';

    
$array[2][0] = 'Nil100';
    
$array[2][1] = 'Y';
    
$array[2][2] = '100';
    
$array[2][3] = '10nilesh';
    
$array[2][4] = 'aakash';
    
$array[2][5] = '_aakash';
    
$array[2][6] = 'aakash_';

    echo 
"array before sorting..."
    
print_r($array);

    
/* $sortedList = recordSort(2d_array, sort_index, reverse, second_level_sort_index_if_duplicates_found_default_is_0 = '0'); */
    
$sortedList recordSort($array405);

    echo 
"array after sorting..."
    
print_r($sortedList);
?>

smileaf at smileaf dot org (2007-01-24 18:34:05)

Ok I was mistaken, after re-reading the previous post the ".$key" is important. What caused the sorting issue for me wasn't that at all. But rather something else.
doing an: asort($records, $flags); before returning fixes the sorting problems.
The sorting problem I was refearing to causes a character based sorting done on numeric data.
so instead of:
1
2
3
...
10
12
20
It was returned back as
1
10
12
2
20
3
...
basically what I was trying to fix in the first place.

smileaf at smileaf dot org (2007-01-24 16:59:20)

This revised version removes the ".$key" from the hash as I wasn't sure why it was there and caused sorting problems for me.
And allows the use of the array flags in both ksort and krsort.
<?
function record_sort($records, $field, $reverse=false, $flags=0)
{
    $hash = array();
    
    foreach($records as $key => $record)
    {
        $hash[$record[$field]] = $record;
    }
    
    ($reverse)? krsort($hash, $flags) : ksort($hash, $flags);
    
    $records = array();
    
    foreach($hash as $record)
    {
        $records []= $record;
    }
    
    return $records;
}
?>

richard at happymango dot me dot uk (2006-11-23 03:52:42)

This is a fixed version of the same function I posted below. Now it will handle duplicate entries in the sorted field. EG: If there were two records that had the name Heathrow it would still work. 

<?php

function record_sort($records$field$reverse=false)
{
    
$hash = array();
    
    foreach(
$records as $key => $record)
    {
        
$hash[$record[$field].$key] = $record;
    }
    
    (
$reverse)? krsort($hash) : ksort($hash);
    
    
$records = array();
    
    foreach(
$hash as $record)
    {
        
$records []= $record;
    }
    
    return 
$records;
}

?>

richard at happymango dot me dot uk (2006-11-22 03:35:16)

This is a function to sort an indexed 2D array by a specified sub array key, either ascending or descending.

It is usefull for sorting query results from a database by a particular field after the query has been returned

This function can be quite greedy. It recreates the array as a hash to use ksort() then back again

By default it will sort ascending but if you specify $reverse as true it will return the records sorted descending 

<?php

function record_sort($records$field$reverse=false)
{
    
$hash = array();
    
    foreach(
$records as $record)
    {
        
$hash[$record[$field]] = $record;
    }
    
    (
$reverse)? krsort($hash) : ksort($hash);
    
    
$records = array();
    
    foreach(
$hash as $record)
    {
        
$records []= $record;
    }
    
    return 
$records;
}

// Example below

$airports = array
(
    array( 
"code" => "LHR""name" => "Heathrow" ),
    array( 
"code" => "LGW""name" => "Gatwick" ),
);

printf("Before: <pre>%s</pre>"print_r($airportstrue));

$airports record_sort($airports"name");

printf("After: <pre>%s</pre>"print_r($airportstrue));

?>

Example Outputs:

Before: Array
(
    [0] => Array ( [code] => LHR, [name] => Heathrow )
    [1] => Array ( [code] => LGW, [name] => Gatwick )
)

After: Array
(
    [0] => Array ( [code] => LGW, [name] => Gatwick )
    [1] => Array ( [code] => LHR, [name] => Heathrow )
)

php at web-in-time dot com (2006-09-05 14:47:19)

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 (2004-06-23 19:38:34)

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 (2004-06-23 04:47:15)

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 (2003-05-20 17:52:42)

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 (2003-04-28 09:54:49)

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 (2003-04-22 16:02:23)

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 (2002-12-03 13:25:00)

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().

(2002-07-31 18:48:55)

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 (2002-07-31 18:32:20)

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 (2002-04-03 13:23:26)

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 (2002-03-02 17:42:22)

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 (2001-11-29 12:37:00)

for sorting CASEINSENSITIVE try
natcasesort()
there's little difference to sort,
but maybe that doesn't matter for you.

freeman at generalresources dot com (2001-05-04 04:51:56)

The asortbyindex($sortarray, $index) looks like sort not asort. The key of the $sortarray was changed.

sweetland at whoadammit dot com (2000-08-15 12:02:39)

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 ($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 (2000-08-02 15:01:44)

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 (2000-02-24 23:26:29)

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.

易百教程