search for in the  
<array_mergearray_pad>
Last updated: Thu, 19 May 2005

array_multisort

(PHP 4, PHP 5)

array_multisort -- Sort multiple or multi-dimensional arrays

Description

bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]] )

Returns TRUE on success or FALSE on failure.

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

The input arrays are treated as columns of a table to be sorted by rows - this resembles the functionality of SQL ORDER BY clause. The first array is the primary one to sort by. The rows (values) in that array that compare the same are sorted by the next input array, and so on.

The argument structure of this function is a bit unusual, but flexible. The first argument has to be an array. Subsequently, each argument can be either an array or a sorting flag from the following lists.

Sorting order flags:

  • SORT_ASC - Sort in ascending order

  • SORT_DESC - Sort in descending order

Sorting type flags:

  • SORT_REGULAR - Compare items normally

  • SORT_NUMERIC - Compare items numerically

  • SORT_STRING - Compare items as strings

No two sorting flags of the same type can be specified after each array. The sorting flags specified after an array argument apply only to that array - they are reset to default SORT_ASC and SORT_REGULAR before each new array argument.

Example 1. Sorting multiple arrays

<?php
$ar1
= array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

In this example, after sorting, the first array will contain "10", "a", 100, 100. The second array will contain 1, 1, "2", 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.

array(4) {
  [0]=> string(2) "10"
  [1]=> string(1) "a"
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(1)
  [1]=> int(1)
  [2]=> string(1) "2"
  [3]=> int(3)
}

Example 2. Sorting multi-dimensional array

<?php
$ar
= array(
       array(
"10", 11, 100, 100, "a"),
       array( 
12, "2"31)
     );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
              
$ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

Example 3. Sorting database results

For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records.

Example data:

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

The data as an array, called data. This would usually, for example, be obtained by looping with mysql_fetch_assoc().

<?php
$data
[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
  
$volume[$key]  = $row['volume'];
  
$edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

The dataset is now sorted, and will look like this:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

Example 4. Case insensitive sorting

Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.

To perform a case insensitive search, force the sorting order to be determined by a lowercase copy of the original array.

<?php
$array
= array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

The above example will output:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)



User Contributed Notes
array_multisort
Michael Oelze at ÄM (myname) ÄT GMXdotDE
25-Apr-2005 11:15
I try array_multisort at first and it seems to work well. But then I program a page with cached datas (the arrays were saved in a session). Suddenly the sort function doesn't seem to work. There was no error in my script, so I try the reference on the variables. Then he manage to sort the arrays again.

So it seems that if you save your Arrays in a session your arrays are global variables and then 'array_multisort' doesn't sort the arrays despite it gives back 'true'.
 You must reference your variables and all work well:

session_start(); // restore variables (Arrays etc.)
.....
.....
array_multisort(&$Array1,&$Array2,&$Array3,...);
....
$_SESSION["Array1"]=$Array1;//
$_SESSION["Array2"]=$Array2;//Save Arrays in Session Data
$_SESSION["Array3"]=$Array3;//
......

Now you can store your Data Arrays in your Session and are able to sort them as you like...
stevec at NO-/ dot /-SPAM dot qiguang dot net
13-Apr-2005 10:19
Be careful when using array_multisort() on copies of arrays, as you might end up changing the original array.  Given the following code:

<?php
   $test1
= array(4,3,2,1);
  
$test2 = $test1;
  
$test3 = array('a', 'b', 'c', 'd');

  
array_multisort($test2, SORT_ASC, $test3);

   echo
'test1:';
  
print_r($test1);
   echo
'test2:';
  
print_r($test2);
   echo
'test3:';
  
print_r($test3);
?>

You would expect:

test1:Array
(
   [0] => 4
   [1] => 3
   [2] => 2
   [3] => 1
)
test2:Array
(
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
)
test3:Array
(
   [0] => d
   [1] => c
   [2] => b
   [3] => a
)

However, if you run the code, you actually get:

test1:Array
(
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
)
test2:Array
(
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
)
test3:Array
(
   [0] => d
   [1] => c
   [2] => b
   [3] => a
)

Note that the original ($test1) ends up being sorted even though it was never called by array_multisort().  To work around this, insert a statement to modify the copy ($test2) before calling array_multisort() on it.  The following code will produce the expected "correct" results:

<?php
   $test1
= array(4,3,2,1);
  
$test2 = $test1;
  
$test3 = array('a', 'b', 'c', 'd');

  
$test2[0] = $test2[0];                // fix
  
array_multisort($test2, SORT_ASC, $test3);
      
   echo
'test1:';
  
print_r($test1);
   echo
'test2:';
  
print_r($test2);
   echo
'test3:';
  
print_r($test3);
?>

This seems to be a resurrection of the closed bug #8130.  Also, someone reported this behavior in bug #32031, but it was incorrectly labeled "bogus" in reference to bug #25359, which is a different issue.
joao at intrasystems dot com dot br
07-Apr-2005 02:27
Exemple of sorting multi-dimensional arrays by one of it's fields:

$result[0]['nome']='Joao';
$result[0]['order']=5;
$result[1]['nome']='Pedro';
$result[1]['order']=1;
$result[2]['nome']='Marcelo';
$result[2]['order']=3;

foreach($result as $res)
     $sortAux[] = $res['order'];

array_multisort($sortAux, SORT_ASC, $result);

print_r($result);

produces:

Array
(
   [0] => Array
       (
           [nome] => Pedro
           [order] => 1
       )

   [1] => Array
       (
           [nome] => Marcelo
           [order] => 3
       )

   [2] => Array
       (
           [nome] => Joao
           [order] => 5
       )

)
Toni
10-Nov-2004 05:30
An example to sort an array by 3 criteria:

$recordset is an array of results from a query to a database, that I sort using $matrix as auxiliary array. First numeric, Second and Third alphabetically.

<?php
for($idx=0;$idx<$toShow;$idx++){
  
$matrix[0][$id]=$recordset[$id][0];
  
$matrix[1][$id]=$recordset[$id][1];
  
$matrix[2][$id]=$recordset[$id][10];   
}

array_multisort($matrix[0], SORT_DESC, SORT_NUMERIC,$matrix[1], SORT_STRING, SORT_ASC,$matrix[2], SORT_STRING, SORT_ASC);
?>
meddle at dzygn.com
05-Oct-2004 09:40
If you want to sort a multidomensional array by key name you cannot use array_multisort. ie: for an array named $archivos that prints like this:

Array
(
   [0] => Array
       (
           [index] => 0
           [name] => test
       )

   [1] => Array
       (
           [index] => 0
           [name] => watertaxi.jpg
       )

   [2] => Array
       (
           [index] => 0
           [name] => 2_0003.JPG
       )

   [3] => Array
       (
           [index] => 0
           [name] => 24A_0025.JPG
       )

   [4] => Array
       (
           [index] => 1
           [name] => _CIMG3501.JPG
       )

)

If I wanted to order by "name" I'd use:

function comparar($a, $b) {
       return strnatcasecmp($a["name"], $b["name"]);
}
usort($archivos, "comparar");

This function performs a case insensitive string comparison using a "natural order" algorithm (strnatcasecmp), resulting in:

Array
(
   [0] => Array
       (
           [index] => 0
           [name] => 2_0003.JPG
       )

   [1] => Array
       (
           [index] => 0
           [name] => 24A_0025.JPG
       )

   [2] => Array
       (
           [index] => 0
           [name] => test
       )

   [3] => Array
       (
           [index] => 0
           [name] => watertaxi.jpg
       )

   [4] => Array
       (
           [index] => 1
           [name] => _CIMG3501.JPG
       )

)
kat dot n0spam at audiogalaxy dot com
24-Aug-2001 12:25
If you're having problems with array_multisort changing variables in global space when it is called inside a function and you're not passing in the function parameters by reference you can alleviate the problem by calling array_multisort with its parameters by reference.

array_multisort(&$a, SORT_DESC, &$b);

More details here in my bug report:
http://www.php.net/bugs.php?id=12936

<array_mergearray_pad>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT