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

uasort

(PHP 4, PHP 5)

uasort 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联

说明

bool uasort ( array &$array , callable $cmp_function )

本函数对数组排序并保持索引和单元之间的关联。

主要用于对那些单元顺序很重要的结合数组进行排序。比较函数是用户自定义的。

参数

array

输入的数组。

cmp_function

用户自定义比较函数的例子请参考 usort()uksort()

返回值

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

范例

Example #1 uasort() 的基本例子

<?php
// Comparison function
function cmp($a$b) {
    if (
$a == $b) {
        return 
0;
    }
    return (
$a $b) ? -1;
}

// Array to be sorted
$array = array('a' => 4'b' => 8'c' => -1'd' => -9'e' => 2'f' => 5'g' => 3'h' => -4);
print_r($array);

// Sort and print the resulting array
uasort($array'cmp');
print_r($array);
?>

以上例程会输出:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

参见


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

用户评论:

alensflash (2012-12-13 19:54:06)

This code is really taking me along time to put it. I'm an amateur on arrays specially multi-dimensional one (T.T) but thanks to all others in here and there, I finally able to put this code together. So, I hope this little code can help solve your problem too as many others had helped me. 

<?php
/*********************************************
*    This code is Sorting on 
*    multi-dimensional array with uasort()
*    $data is 4 Dimensional Array 
*
*********************************************/

$data = array(
    array(
        
'attributes' => array(
            array(
'name' => 'Micrologic''age' => '2.0'),
            array(
'name' => 'Pole''age' => '4P')
        ),
        
'ref' => '33463E',
        
'price' => '5.500'
    
),
    array(
        
'attributes' => array(
            array(
'name' => 'Micrologic''age' => '2.0'),
            array(
'name' => 'Pole''age' => '3P')
        ),
        
'ref' => '33460E',
        
'price' => '7.500'
    
),
    array(
        
'attributes' => array(
            array(
'name' => 'Micrologic''age' => '5.0'),
            array(
'name' => 'Pole''age' => '4P')
        ),
        
'ref' => '33549E',
        
'price' => '2.500'
    
),
    array(
        
'attributes' => array(
            array(
'name' => 'Micrologic''age' => '5.0'),
            array(
'name' => 'Pole''age' => '3P')
        ),
        
'ref' => '33546E',
        
'price' => '7.500'
    
)
);

/*** uasort function ***/
function compareRef($a$b){ 
    return 
strnatcmp($a['ref'],$b['ref']); 
}
uasort($data'compareRef');

/*** Print $data ***/
echo "--SORT BY REF-- <br />";
foreach(
$data as $idx => $prod) {    
    foreach(
$prod['attributes'] as $attrib)
        echo 
$attrib['name'].' - '.$attrib['age'].", ";
    
    echo 
" = ".$prod['ref']." & Rp.".$prod['price']."<br />";
}
?>

(^^)b

iborodikhin at gmail dot com (2012-11-22 08:32:15)

To shuffle assoc array preserving keys just do this:
<?php uasort(
    
$array,
    function (
$a$b) {
        return 
mt_rand(01) > : -1;
    }
); 
?>

Said Dashuk (2011-10-11 22:33:03)

My simple and effective solution for sort multi-dimensional array by any key:

<?php
function sort_by_key ($arr,$key) {
    global 
$key2sort;
    
$key2sort $key;
    
uasort($arr'sbk');
    return (
$arr);
}
function 
sbk ($a$b) {global $key2sort; return (strcasecmp ($a[$key2sort],$b[$key2sort]));}
?>

clem at fragment dot at (2011-08-31 04:57:52)

for a simple case insensitive compare you can use this (php >= 5.3):

<?php
$greetings 
= array('howdy''Hey''aloha he');

uasort($a, function($a$b){ return strcasecmp($a$b); });

//$a == array('aloha he', 'howdy', 'Hey');
?>

englishman at bigmir dot net (2011-07-02 04:44:58)

In case you need to sort an associative array by one of its keys, this function might be useful:

<?php
function sortByOneKey(array $array$key$asc true) {
    
$result = array();
        
    
$values = array();
    foreach (
$array as $id => $value) {
        
$values[$id] = isset($value[$key]) ? $value[$key] : '';
    }
        
    if (
$asc) {
        
asort($values);
    }
    else {
        
arsort($values);
    }
        
    foreach (
$values as $key => $value) {
        
$result[$key] = $array[$key];
    }
        
    return 
$result;
}

?>

Consider the following example:

<?php

$users 
= array(
    
=> array('name' => 'John''age' => 35),
    
=> array('name' => 'Alice''age' => 23),
    
=> array('name' => 'Bob''age' => 26)
);
        
$sortedByNameAsc sortByOneKey($users'name');
$sortedByNameDesc sortByOneKey($users'name'false);
        
echo 
"Sorted by Name in ascending order: ";
echo 
"<pre>" print_r($sortedByNameAsctrue) . "</pre>";
echo 
"<br /><br />Sorted by Name in descending order: ";
echo 
"<pre>" print_r($sortedByNameDesctrue) . "</pre>";

?>

The output will be the following: 

Sorted by Name in ascending order: 
Array
(
    [2] => Array
        (
            [name] => Alice
            [age] => 23
        )

    [3] => Array
        (
            [name] => Bob
            [age] => 26
        )

    [1] => Array
        (
            [name] => John
            [age] => 35
        )

)

Sorted by Name in descending order: 
Array
(
    [1] => Array
        (
            [name] => John
            [age] => 35
        )

    [3] => Array
        (
            [name] => Bob
            [age] => 26
        )

    [2] => Array
        (
            [name] => Alice
            [age] => 23
        )

)

yannick dot battail at gmail dot com (2010-11-17 06:37:32)

An Example using anonymous function.
Anonymous functions make some time the code easier to understand.
<?php
$fruits 
= array('Orange9','Orange11','Orange10','Orange6','Orange15');
uasort $fruits , function ($a$b) {
            return 
strnatcmp($a,$b); // or other function/code
        
}
    );
print_r($fruits);
?>
returns
Array
(
    [3] => Orange6
    [0] => Orange9
    [2] => Orange10
    [1] => Orange11
    [4] => Orange15
)

magikMaker (2010-10-19 02:48:49)

a quick reminder on the syntax if you want to use uasort in a Class or Object:

<?php

// procedural:
uasort($collection'my_sort_function');

// Object Oriented
uasort($collection, array($this'mySortMethod'));

// Objet Oriented with static method
uasort($collection, array('self''myStaticSortMethod'));

?>

Yves (2010-10-08 00:20:34)

Took me some time to figure that out:
the user function must return an *integer*, if you return a float, you may not get the expected result.

<?php 
  $a 
= ('a' => 0.9'b' => 0.7'c' => 0.8);

  function 
sorting($a$b) { return $a $b; } 

  
// The function above will not =work, you have to

  
function sorting($a$b)
  {
   
$d $a $b;
    return 
$d ? -: ($d 0);
  } 
?>

phire_sk (2010-10-05 14:19:46)

I tried using some of the previous built multisorts, but they weren't working as expected.

So, I made my own Class, and it seems to work wonderfully.

Here is the code:

<?php
/************************************
*    Allows sorting multi-dimensional
*    arrays by a specific key and in
*    asc or desc order
**/
class multiSort
{
    var 
$key;    //key in your array

    //runs the sort, and returns sorted array
    
function run ($myarray$key_to_sort$type_of_sort '')
    {
        
$this->key $key_to_sort;
        
        if (
$type_of_sort == 'desc')
            
uasort($myarray, array($this'myreverse_compare'));
        else
            
uasort($myarray, array($this'mycompare'));
            
        return 
$myarray;
    }
    
    
//for ascending order
    
function mycompare($x$y)
    {
        if ( 
$x[$this->key] == $y[$this->key] )
            return 
0;
        else if ( 
$x[$this->key] < $y[$this->key] )
            return -
1;
        else
            return 
1;
    }
    
    
//for descending order
    
function myreverse_compare($x$y)
    {
        if ( 
$x[$this->key] == $y[$this->key] )
            return 
0;
        else if ( 
$x[$this->key] > $y[$this->key] )
            return -
1;
        else
            return 
1;
    }
}
?>

stephan dot hoyer at netresearch dot de (2010-07-22 05:17:42)

To sort string containing Umlauts you can use this callback function:

<?php
    
function sortWUmlauts($s1$s2)
    {
        
$search = array('?','?','?','?');
        
$replace = array('A','O','U','s');
        return 
strcmp(
           
str_ireplace($search$replace$s1),
           
str_ireplace($search$replace$s2)
           );
    }
?>

simply call:

<?php uasort($array'sortWUmlauts'); ?>

paul at webtop-designs dot com (2009-11-30 13:40:07)

Just expanding on php arobase kochira period com's method:

If you are looking to sort a multi-D array by a specific column and have entries in both upper and lower case, simply drop the entries to lowercase before doing the strcmp.

<?php
$dirs 
= array(
  array(
'name' => 'First Folder''path' => 'sompath'),
  array(
'name' => 'second folder''path' => 'sompath2'),
  array(
'name' => 'Third Folder''path' => 'sompath3')
);

function 
so($a$b) { 
    return (
strcmp (strtolower($a['name']), strtolower($b['name'])));
}
?>

Alt_F4 (2009-10-09 20:34:25)

I couldn't work out a way to specify what element to sort by using the existing php functions - maybe I didn't look hard enough?? So i wrote my own multidimensional array sorting class. 

<?php

$stock 
= array(array("id" => 1,"item" => "hat",
                 
"number" => 5,    "price" => 15),
                array(
"id" => 5,"item" => "shoes",
                 
"number" => 1,    "price" => 50),
                array(
"id" => 3,"item" => "tie",
                 
"number" => 2,    "price" => 30));
                 
$sort = new multiSort();

//will sort the array by id in ascending order
print_r ($sort->sortArray($stock,'id','rcmp'));

//will sort the array by id in descending order
print_r ($sort->sortArray($stock,'id','cmp'));

//can also be used like so (specifying the index of the array)
print_r ($sort->sortArray($stock,'0','rcmp'));

//////////////////////////////////////////////////////

class multiSort {

    function 
sortArray($array,$parameter,$_function) { return $this->_uasort($array,$_function,$parameter); }
    
    function 
cmp ($a$b$p) { return (strcmp ($a[$p],$b[$p]));}
    
    function 
rcmp ($a$b$p) { return -* (strcmp ($a[$p],$b[$p]));}
    
    function 
_uasort($array,$func,$param) {
        for(
$i=0;$i<sizeof($array);$i++) {
            
$tmp $i;
            for(
$j=1;$j<sizeof($array);$j++) {
                
$result $this->$func($array[$tmp],$array[$j],$param);    
                if(
$result == -1) {
                    
$array $this->arraySwap($array,$tmp,$j);
                    
$tmp $j;
                } 
            }
        }    
        return 
$array;
    }
    
    function 
arrayswap($arr$src$dst) { 
        
$tmp $arr[$dst]; 
        
$arr[$dst] = $arr[$src]; 
        
$arr[$src] = $tmp
        return 
$arr
    } 
}
//////////////////////////////////////////////////////////
?>

hope someone finds this useful.

php arobase kochira period com (2008-06-08 04:13:44)

Difference between uasort() and usort(), the missing example ...

<?php
  $arr 
= array ( 10 => array('id' => 'dix',  'aa' => '1010'),
                
100 => array('id' => 'cent''aa' => '100100'),
                  
=> array('id' => 'deux''aa' => '22'), 
                  
=> array('id' => 'sept''aa' => '77'));

  
// id sorting
  
function so ($a$b) { return (strcmp ($a['id'],$b['id']));    }
?>

*** uasort($arr, 'so') output:

<?php Array (
    [
100] => Array
        (
            [
id] => cent
            
[aa] => 100100
        
)

    [
2] => Array
        (
            [
id] => deux
            
[aa] => 22
        
)

    [
10] => Array
        (
            [
id] => dix
            
[aa] => 1010
        
)

    [
7] => Array
        (
            [
id] => sept
            
[aa] => 77
        
))?>

*** usort($arr, 'so') output:

<?php Array (
    [
0] => Array
        (
            [
id] => cent
            
[aa] => 100100
        
)

    [
1] => Array
        (
            [
id] => deux
            
[aa] => 22
        
)

    [
2] => Array
        (
            [
id] => dix
            
[aa] => 1010
        
)

    [
3] => Array
        (
            [
id] => sept
            
[aa] => 77
        
))?>

joeseed86 at gmail dot com (2007-01-04 09:54:37)

Using uasort to alphabetically sort nested objects:

In this example, a "collection" object contains an array of "dataItem" objects which consist of a string name, a string attribute x and an arbitrary integer y. 

This code allows you to sort the dataset by any of the dataItem attributes, or the order in which they were originally added to the set.

I'm using PHP 4.23 at work at the moment for legacy reasons, so I wrote the example following that object model.

<?php
class dataItem
{
    var 
$name;
    var 
$x;
    
    
//Constructor
    
function dataItem($name,$x,$y)
    {
        
$this->name $name;
        
$this->$x;
        
$this->$y;
    }
}

class 
collection
{
    var 
$dataSet = array();
    
    
//Creates a new data item and adds it to our array
    
function add($name,$x,$y)
    {
        
$this->dataSet[] = new dataItem($name,$x,$y);
    }
    
    
//The wrapper sort function
    
function sortDataSet($s)
    {
        
//Sort by the given parameter
        
switch($s)
        {
            case 
"name":
                
//Note use of array to reference member method of this object in callback
                
uasort($this->dataSet,array($this,"cmpName"));
                break;
            
            case 
"x":
                
uasort($this->dataSet,array($this,"cmpX"));
                break;
                
            case 
"y":
                
uasort($this->dataSet,array($this,"cmpY"));
                break;                
            
            case 
"added":
            default:
                
//Re-sort array by original keys
                
ksort($this->dataSet);        
        }
    }

    
//Callback function for sorting by name
    //$a and $b are dataItem objects
    
function cmpName($a,$b)
    {
        
//Use sort() for simple alphabetical comparison
        //Convert to lowercase to ensure consistent behaviour
        
$sortable = array(strtolower($a->name),strtolower($b->name));
        
$sorted $sortable;
        
sort($sorted);    
        
        
//If the names have switched position, return -1. Otherwise, return 1.
        
return ($sorted[0] == $sortable[0]) ? -1;
    }
    
    
//Callback function for sorting by x
    //$a and $b are dataItem objects
    
function cmpX($a,$b)
    {
        
//Use sort() for simple alphabetical comparison
        //Convert to lowercase to ensure consistent behaviour
        
$sortable = array(strtolower($a->x),strtolower($b->x));
        
$sorted $sortable;
        
sort($sorted);    
        
        
//If the names have switched position, return -1. Otherwise, return 1.
        
return ($sorted[0] == $sortable[0]) ? -1;
    }
    
    
//Callback function for sorting by y
    //$a and $b are dataItem objects
    
function cmpY($a,$b)
    {        
        
//If $a's y attribute >= $b's y attribute, return 1. Otherwise, return -1.
        
return ($a->>= $b->y) ? : -1;
    }    

}

//Create a collection object
$myCollection = new collection();

//Add a few "records"
$myCollection->add("pancake","egg",7);
$myCollection->add("France","Paris",2);
$myCollection->add("Naked Gun","Leslie Nielsen",1);
$myCollection->add("OSX","huge icons",33);
$myCollection->add("telephone","keypad",-3);

//Test the output

//Sort by name:
$myCollection->sortDataSet("name");
print_r($myCollection->dataSet);

//Sort by x
$myCollection->sortDataSet("x");
print_r($myCollection->dataSet);

//Sort by y
$myCollection->sortDataSet("y");
print_r($myCollection->dataSet);

//Sort by order added
$myCollection->sortDataSet("added");
print_r($myCollection->dataSet);

?>

Will give this output (Anotated and re-formatted for ease of reading):

Sorted by name:
France         Paris            2
Naked Gun      Leslie Nielsen   1
OSX            huge icons       33
pancake        egg              7
telephone      keypad          -3

Sorted by x:
pancake        egg              7
OSX            huge icons       33
telephone      keypad          -3
Naked Gun      Leslie Nielsen   1
France         Paris            2

Sorted by y:
telephone      keypad          -3
Naked Gun      Leslie Nielsen   1
France         Paris            2
pancake        egg              7
OSX            huge icons       33

Sorted as added:
pancake        egg              7
France         Paris            2
Naked Gun      Leslie Nielsen   1
OSX            huge icons       33
telephone      keypad          -3

This is obviously a trivial case, but it can be very useful for larger data structures.

rlynch at lynchmarks dot com (2005-05-16 17:36:23)

A subtle bug, corrected...

<?php
function masort(&$data$sortby)
{
   static 
$sort_funcs = array();
  
   if (empty(
$sort_funcs[$sortby])) {
       
$code "\$c=0;";
       foreach (
split(','$sortby) as $key) {
         
$array array_pop($data);
         
array_push($data$array);
         if(
is_numeric($array[$key]))
           
$code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) ) return \$c;";
         else
           
$code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
       }
       
$code .= 'return $c;';
       
$sort_func $sort_funcs[$sortby] = create_function('$a, $b'$code);
   } else {
       
$sort_func $sort_funcs[$sortby];
   }
   
$sort_func $sort_funcs[$sortby];
   
uasort($data$sort_func);
}
?> 

Note that 

$code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) ) return \$c;";

Has had the "return \$c" added.  Ultimately what the method is trying to accomplish is to build a chain of sort-order precedence.  But this requires each evaluation to short-circuit out with a return.  It was missing.

Peace

lucas dot karisny at linuxmail dot org (2005-02-12 18:09:15)

The following is a modification of the dholme/messju masort func using david's float code with automatic data type detection.  As long as the value isn't a string numeral (I.E. "1", '13.4') this should sort strings and numbers without having to explicity set which they are.

<?php
function masort(&$data$sortby)
{
   static 
$sort_funcs = array();
  
   if (empty(
$sort_funcs[$sortby])) {
       
$code "\$c=0;";
       foreach (
split(','$sortby) as $key) {
         
$array array_pop($data);
         
array_push($data$array);
         if(
is_numeric($array[$key]))
           
$code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) );";
         else
           
$code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
       }
       
$code .= 'return $c;';
       
$sort_func $sort_funcs[$sortby] = create_function('$a, $b'$code);
   } else {
       
$sort_func $sort_funcs[$sortby];
   }
   
$sort_func $sort_funcs[$sortby];
   
uasort($data$sort_func);
}
?>

siefer at sym dot net (2004-10-04 02:24:48)

Hello naholyr at yahoo dot fr!
should it be
$cmp = create_function('$a, $b', "return $cmp_val;");
?
this works with my arrays ;-)
regards, Christopher

marek at lewczuk dot com (2004-05-27 04:01:22)

Below another array sorting function - you can use many keys, whether order type is ascendant or descendant, if values of given key should be treat as string or numeric, if array keys should be preserved. This function is locale-safe - it means that string sorting will be based on setLocale settings. You should be aware that I did not make comprehensive tests, so be careful...
// my locales
SetLocale(LC_COLLATE,"pl_PL.UTF-8");
SetLocale(LC_CTYPE, "pl_PL.UTF-8");
function Array_Sort ($array, $arguments = Array(), $keys = true) {

// comparing function code
$code = "";

// foreach sorting argument (array key)
foreach ($arguments as $argument) {

// order field
$field = substr($argument, 2, strlen($argument));

// sort type ("s" -> string, "n" -> numeric)
$type = $argument[0];

// sort order ("+" -> "ASC", "-" -> "DESC")
$order = $argument[1];

// add "if" statement, which checks if this argument
should be used
$code .= "if (!Is_Numeric(\$result) || \$result == 0) ";

// if "numeric" sort type
if (strtolower($type) == "n") $code .= $order == "-" ? "\$result = (\$a['{$field}'] > \$b['{$field}'] ? -1 : (\$a['{$field}'] < \$b['{$field}'] ? 1 : 0));" : "\$result = (\$a['{$field}'] > \$b['{$field}'] ? 1 : (\$a['{$field}'] < \$b['{$field}'] ? -1 : 0));";

// if "string" sort type
else $code .= $order == "-" ? "\$result = strcoll(\$a['{$field}'], \$b['{$field}']) * -1;" : "\$result = strcoll(\$a['{$field}'], \$b['{$field}']);";
}

// return result
$code .= "return \$result;";

// create comparing function
$compare = create_function('$a, $b', $code);

// sort array and preserve keys
if ($keys) uasort($array, $compare);

// sort array, but not preserve keys
else usort($array, $compare);

// return array
return $array;
}
Example array:
$array['sdsd'] = array("dir" => 1, "name" => "sas", "olek" => "sdsd");
$array['sds2'] = array("dir" => 2, "name" => "&#347;as", "olek" => "t");
Example - preserve keys:
print_r(Array_Sort($array, Array("s-name", "n-dir", "s+olek")));
Array
(
[sds2] => Array
(
[dir] => 1
[name] => &#347;as
[olek] => t
)
[sdsd] => Array
(
[dir] => 1
[name] => sas
[olek] => sdsd
)
)
Example - without preserving keys:
print_r(Array_Sort($array, Array("s-name", "n-dir", "s+olek")), false);
Array
(
[0] => Array
(
[dir] => 1
[name] => &#347;as
[olek] => t
)
[1] => Array
(
[dir] => 1
[name] => sas
[olek] => sdsd
)
)
Enyoj

david [__at__] castlelaing.com (2004-05-10 09:28:43)

WARNING:-Regarding remmy.cjb.net (22-Oct-2003 05:57) mutisort() function:

Sorting by floating point numbers doesn't work in the current function. Use the modified version below if you want to sort by a floating point column.

<?php
// Based on the other notes given before.
// Sorts an array (you know the kind) by key
// and by the comparison operator you prefer.

// Note that instead of most important criteron first, it's
// least important criterion first.

// The default sort order is ascending, and the default sort
// type is strnatcmp.

// function multisort($array[, $key, $order, $type]...)
function multisort($array)
{
   for(
$i 1$i func_num_args(); $i += 3)
   {
       
$key func_get_arg($i);
       if (
is_string($key)) $key '"'.$key.'"';
      
       
$order true;
       if(
$i func_num_args())
           
$order func_get_arg($i 1);
      
       
$type 0;
       if(
$i func_num_args())
           
$type func_get_arg($i 2);

       switch(
$type)
       {
           case 
1// Case insensitive natural.
               
$t 'strcasecmp($a[' $key '], $b[' $key '])';
               break;
           case 
2// Numeric.
               
$t '($a[' $key '] == $b[' $key ']) ? 0:(($a[' $key '] < $b[' $key ']) ? -1 : 1)';
               break;
           case 
3// Case sensitive string.
               
$t 'strcmp($a[' $key '], $b[' $key '])';
               break;
           case 
4// Case insensitive string.
               
$t 'strcasecmp($a[' $key '], $b[' $key '])';
               break;
           default: 
// Case sensitive natural.
               
$t 'strnatcmp($a[' $key '], $b[' $key '])';
               break;
       }
       echo 
$t;
       
usort($arraycreate_function('$a, $b''; return ' . ($order '' '-') . '(' $t ');'));
   }
   return 
$array;
}
?>

dn dot php at gmx dot de (2003-11-23 16:34:28)

regarding remmy.cjb.net (22-Oct-2003 05:57) note:
The "multisort" function is not working. Try the following example.
( I hope this and your note will be deleted soon.)
..- Denis

<?php
$a 
= array(
    array(
'c1' => 1'c2' => 1'c3' => 1'c4' => 1),
    array(
'c1' => 1'c2' => 1'c3' => 1'c4' => 2),
    array(
'c1' => 1'c2' => 1'c3' => 2'c4' => 1),
    array(
'c1' => 1'c2' => 1'c3' => 2'c4' => 2)
);

echo(
'<pre>');
print_r(multisort($a"'c4'"true2,"'c3'"true2,"'c2'"true2,"'c1'"true2));
echo(
'</pre>');
?>

remmy.cjb.net (2003-10-21 23:57:09)

Hope this helps!

- Remmy

<?php

// Based on the other notes given before.
// Sorts an array (you know the kind) by key
// and by the comparison operator you prefer.

// Note that instead of most important criteron first, it's
// least important criterion first.

// The default sort order is ascending, and the default sort
// type is strnatcmp.

// function multisort($array[, $key, $order, $type]...)
function multisort($array)
{
    for(
$i 1$i func_num_args(); $i += 3)
    {
        
$key func_get_arg($i);
        
        
$order true;
        if(
$i func_num_args())
            
$order func_get_arg($i 1);
        
        
$type 0;
        if(
$i func_num_args())
            
$type func_get_arg($i 2);

        switch(
$type)
        {
            case 
1// Case insensitive natural.
                
$t 'strcasenatcmp($a[' $key '], $b[' $key '])';
                break;
            case 
2// Numeric.
                
$t '$a[' $key '] - $b[' $key ']';
                break;
            case 
3// Case sensitive string.
                
$t 'strcmp($a[' $key '], $b[' $key '])';
                break;
            case 
4// Case insensitive string.
                
$t 'strcasecmp($a[' $key '], $b[' $key '])';
                break;
            default: 
// Case sensitive natural.
                
$t 'strnatcmp($a[' $key '], $b[' $key '])';
                break;
        }

        
uasort($arraycreate_function('$a, $b''return ' . ($order '' '-') . '(' $t ');'));
    }

    return 
$array;
}

$a = array(
    array(
'id' => 1'name' => 'apple'),
    array(
'id' => 2'name' => 'orange'),
    array(
'id' => 8'name' => 'banana'),
    array(
'id' => 8'name' => 'grapefruit'),
    array(
'id' => 9'name' => 'smoke'),
    array(
'id' => 1'name' => 'screen')
);

// This works like MYSQL 'ORDER BY id DESC, name ASC'
// Note the quoting of string literal keys.
echo('<pre>');
print_r(multisort($a"'name'"true0"'id'"false2));
echo(
'</pre>');

?>

cablehead (2003-09-16 09:08:40)

dholmes we turned your masort function into a smarty plugin:
http://www.phpinsider.com/smarty-forum/viewtopic.php?t=1079
messju contributed the following performance improvements.
function masort(&$data, $sortby)
{
static $sort_funcs = array();

if (empty($sort_funcs[$sortby])) {
$code = "\$c=0;";
foreach (split(',', $sortby) as $key) {
$code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
}
$code .= 'return $c;';
$sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
} else {
$sort_func = $sort_funcs[$sortby];
}
$sort_func = $sort_funcs[$sortby];
uasort($data, $sort_func);
}
thank you for the cool function!

php at eden2 dot com (2003-07-17 04:36:37)

Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()?
After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this:
"john" => "$23.12"
"tim" => "$6.50"
"bob" => "$18.54"
and getting back:
"tim" => "$6.50"
"bob" => "$18.54"
"john" => $23.12"
(assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)

naholyr at yahoo dot fr (2003-01-10 09:35:44)

You can sort a multidimensionnal array by any of its key with this function:
function multi_sort($array, $key)
{
$cmp_val="((\$a['$key']>\$b['$key'])?1:
((\$a['$key']==\$b['$key'])?0:-1))";
$cmp=create_function('$a, $b', "return $body;");
uasort($array, $cmp);
return $array;
}
example:
$myarray = array(
array("name"=>"kernighan", "language"=>"c"),
array("name"=>"lerdorf", "language"=>"php"),
array("name"=>"Stroustrup", "language"=>"c++"),
array("name"=>"Gosling", "language"=>"java")
);
multi_sort($myarray, "name") returns:
name=Gosling language=java
name=Kernighan language=c
name=Lerdorf language=php
name=Stroustrup language=c++

dholmes at jccc d0t net (2002-10-09 14:27:26)

Here is a little sort function that actually uses a dynamic callback for usort to do it's thing.
It assumes your data is in the form of:
$data = array(
array('ID'=>'6','LAST'=>'Holmes','FIRST'=>'Dan'),
array('ID'=>'1234','LAST'=>'Smith','FIRST'=>'Agent K'),
array('ID'=>'2','LAST'=>'Smith','FIRST'=>'Agent J'),
array('ID'=>'4','LAST'=>'Barney','FIRST'=>'Bob'));
Now, you want to sort on one or more cols, don't you?
masort($data, 'LAST,FIRST');
or
masort($data,array('FIRST','ID'));
Of course you could add a bunch to it (like numeric comparison if appropriate, desc/asc, etc) but it works for me.
function masort(&$data, $sortby){
if(is_array($sortby)){
$sortby = join(',',$sortby);
}
uasort($data,create_function('$a,$b','$skeys = split(\',\',\''.$sortby.'\');
foreach($skeys as $key){
if( ($c = strcasecmp($a[$key],$b[$key])) != 0 ){
return($c);
}
}
return($c); '));
}
Notice that I am splitting the string in the comparison function? While this is certainly slower, it was the only way I would find to "pass" and "array". If anyone has a better way, please suggest. Then inside, we (string) compare the values only moving to the next key if the values are the same...and so on, and so on.

stilgar_cpsNOSPAM at zipmail dot NOSPAMcom dot br (2001-09-05 14:30:18)

Use example:
$array[0]['Fator1']=7;
$array[0]['Fator2']="Name";
$array[1]['Fator1']=5;
$array[1]['Fator2']="Name";
$array[2]['Fator1']=7;
$array[2]['Fator2']="NameDiferente";
.....
We want to order by Fator1, then Fator2, then:
function Compare($ar1, $ar2)
{
if ($ar1['Fator1']<$ar2['Fator1'])
return -1;
else if ($ar1['Fator1']>$ar2['Fator1'])
return 1;
if ($ar1['Fator2']<$ar2['Fator2'])
return -1;
else if ($ar1['Fator2']>$ar2['Fator2'])
return 1;
return 0;
}
To sort now, we use:
uasort($array, 'Compare');

易百教程