Update to array_msort(): instead of eval() using call_user_func_array(). If we get column sorting via $_GET it would be a serious security hole.
Now it also accepts multiple options for each column:
<?php
$arr2 = array_msort($arr1, array('name'=>array(SORT_DESC,SORT_REGULAR), 'cat'=>SORT_ASC));
?>
Btw. this function is automatically case-insensitive, as you can see use of strtolower().
<?php
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$params = array();
foreach ($cols as $col => $order) {
$params[] =& $colarr[$col];
$params = array_merge($params, (array)$order);
}
call_user_func_array('array_multisort', $params);
$ret = array();
$keys = array();
$first = true;
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
if ($first) { $keys[$k] = substr($k,1); }
$k = $keys[$k];
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
$first = false;
}
return $ret;
}
?>
array_multisort
(PHP 4, PHP 5)
array_multisort — Sort multiple or multi-dimensional arrays
Description
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.
Parameters
- arr
-
An array being sorted.
- arg
-
Optionally another array, or sort options for the previous array argument: SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING.
- ...
-
Additional arg 's.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Sorting multiple arrays
<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);
var_dump($ar1);
var_dump($ar2);
?>
In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 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]=> int(0)
[1]=> int(10)
[2]=> int(100)
[3]=> int(100)
}
array(4) {
[0]=> int(4)
[1]=> int(1)
[2]=> int(2)
[3]=> int(3)
}
Example #2 Sorting multi-dimensional array
<?php
$ar = array(
array("10", 11, 100, 100, "a"),
array( 1, 2, "2", 3, 1)
);
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
)
See Also
- usort() - Sort an array by values using a user-defined comparison function
- The comparison of array sorting functions
array_multisort
21-Jun-2009 07:38
21-Jun-2009 04:16
A more inuitive way of sorting multidimensional arrays using array_msort() in just one line, you don't have to divide the original array into per-column-arrays:
<?php
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$arr2 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
debug($arr1, $arr2);
arr1:
0:
id: 1 (int)
name: aA (string:2)
cat: cc (string:2)
1:
id: 2 (int)
name: aa (string:2)
cat: dd (string:2)
2:
id: 3 (int)
name: bb (string:2)
cat: cc (string:2)
3:
id: 4 (int)
name: bb (string:2)
cat: dd (string:2)
arr2:
2:
id: 3 (int)
name: bb (string:2)
cat: cc (string:2)
3:
id: 4 (int)
name: bb (string:2)
cat: dd (string:2)
0:
id: 1 (int)
name: aA (string:2)
cat: cc (string:2)
1:
id: 2 (int)
name: aa (string:2)
cat: dd (string:2)
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[\''.$col.'\'],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
?>
16-May-2009 07:45
Here is useful example based on za at byza dot it solution to sort multidimensional objects by any dimension.
za at byza dot it
<?php
/* Example structure */
class person{
function __construct($firstName, $lastName, $title, $position){
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->title = new title($title);
$this->position = new position($position);
}
}
class title{
function __construct($name){
$this->name = $name;
}
}
class position{
function __construct($name){
$this->name = $name;
}
}
$array[] = new person('Piotr', 'Sobiepanek', 'b', 'b');
$array[] = new person('Piotr', 'Kowalski', 'b', 'a');
$array[] = new person('Piotr', 'Michalski', 'a', 'a');
$array[] = new person('Jozef', 'Smietana', 'a', 'b');
$array[] = new person('Jozef', 'Cmietana', 'a', 'b');
$array[] = new person('Marcin', 'Kondraciuk', 'c', 'b');
$array[] = new person('Maksym', 'Kondraciuk', 'c', 'd');
$array[] = new person('Ambrozy', 'Kondraciuk', 'c', 'd');
$array[] = new person('Alojzy', 'Kondraciuk', 'c', 'd');
array_sort($array, 'title->name', 'position->name', 'lastName');
print_r($array);
/* Source */
function hod(&$base, $path){
$keys = explode("->", $path);
$keys[0] = str_replace('$', '', $keys[0]);
$expression = '$ret = ';
$expression.= '$';
foreach ($keys as $key){
if (++$licz == 1){
$expression.= 'base->';
} else {
$expression.= $key.'->';
}
}
$expression = substr($expression, 0, -2);
$expression.= ';';
eval($expression);
return $ret;
}
function array_sort_func($a,$b=NULL) {
static $keys;
if($b===NULL) return $keys=$a;
foreach($keys as $k) {
if($k[0]=='!') {
$k=substr($k,1);
if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
return strcmp(hod($b, '$b->'.$k),hod($a, '$a->'.$k));
}
}
else if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
return strcmp(hod($a, '$a->'.$k),hod($b, '$b->'.$k));
}
}
return 0;
}
function array_sort(&$array) {
if(!$array) return $keys;
$keys=func_get_args();
array_shift($keys);
array_sort_func($keys);
usort($array,"array_sort_func");
}
?>
28-Apr-2009 02:08
I wrote a function to sort a multidimensional array by multiple columns in ascending and descending order.
Sample array:
<?php
$my_array=array(
array('id'=>1, 'surname'=>'rossi', 'name'=>'mario', 'group'=>'admin'),
array('id'=>2, 'surname'=>'rossi', 'name'=>'giovanni', 'group'=>'user'),
array('id'=>3, 'surname'=>'verdi', 'name'=>'luigi', 'group'=>'user'),
array('id'=>4, 'surname'=>'verdi', 'name'=>'franco', 'group'=>'guest'),
array('id'=>5, 'surname'=>'bianchi', 'name'=>'mario', 'group'=>'guest')
);
?>
Example: <?php array_sort($my_array,'!group','surname'); ?>
Output: sort the array DESCENDING by group and then ASCENDING by surname. Notice the use of ! to reverse the sort order. Rows order will be: 2,3,5,4,1
The function code:
<?php
function array_sort_func($a,$b=NULL) {
static $keys;
if($b===NULL) return $keys=$a;
foreach($keys as $k) {
if(@$k[0]=='!') {
$k=substr($k,1);
if(@$a[$k]!==@$b[$k]) {
return strcmp(@$b[$k],@$a[$k]);
}
}
else if(@$a[$k]!==@$b[$k]) {
return strcmp(@$a[$k],@$b[$k]);
}
}
return 0;
}
function array_sort(&$array) {
if(!$array) return $keys;
$keys=func_get_args();
array_shift($keys);
array_sort_func($keys);
usort($array,"array_sort_func");
}
?>
29-Mar-2009 05:04
I was (as near everyone here :-) looking to sort 2-dimensional arrays by certain fields in the associative sub-arrays.
What I didn't like about the documentation examples is that you need to loop through the input array to create sub arrays first, then use those in the function call.
"php a-t-the-r-a-t-e chir.ag" (http://www.php.net/manual/en/function.array-multisort.php#60401) wrote a quite cunning wrapper function, I rewrote it slightly, changing variable names and adding comments (for my sanity :-) mostly.
One snag I found: the input array is passed to array_multisort as last argument, but the changed array is not the one that is returned. Passing it by reference fixed that. This seems to be caused by the whole thing sitting inside the call_user_func_array, as shown below.
<?php
$points = array(1, 5, 2, 2);
$names = array('peter', 'mike', 'john Zoo', 'john Ab');
$source = array (
array ( 'points' => 1, 'name' => 'Peter'),
array ( 'points' => 5, 'name' => 'Mike'),
array ( 'points' => 2, 'name' => 'John Zoo'),
array ( 'points' => 2, 'name' => 'John Ab')
);
call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, $source)); // doesn't work
print_r($source);
call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, &$source)); // works!
print_r($source);
// Call like arrayColumnSort('points', SORT_DESC, SORT_NUMERIC, 'name', SORT_ASC, SORT_STRING, $source);
// Slightly adapted from http://www.php.net/manual/en/function.array-multisort.php#60401
// arrayColumnSort(string $field, [options, ], string $field2, [options, ], .... , $array) /
//____________________
// arrayColumnSort() /
function arrayColumnSort() {
$args = func_get_args();
$array = array_pop($args);
if (! is_array($array)) return false;
// Here we'll sift out the values from the columns we want to sort on, and put them in numbered 'subar' ("sub-array") arrays.
// (So when sorting by two fields with two modifiers (sort options) each, this will create $subar0 and $subar3)
foreach($array as $key => $row) // loop through source array
foreach($args as $akey => $val) // loop through args (fields and modifiers)
if(is_string($val)) // if the arg's a field, add its value from the source array to a sub-array
${"subar$akey"}[$key] = $row[$val];
// $multisort_args contains the arguments that would (/will) go into array_multisort(): sub-arrays, modifiers and the source array
$multisort_args = array();
foreach($args as $key => $val)
$multisort_args[] = (is_string($val) ? ${"subar$key"} : $val);
$multisort_args[] = &$array; // finally add the source array, by reference
call_user_func_array("array_multisort", $multisort_args);
return $array;
}
?>
15-Jan-2009 07:38
I had a function to make a sort on a 2D array and I wanted to sort an array using a column that usualy contains numeric values but also strings.
Lets say we have this array :
Array (
[0] => Array ( "name" = "12000" ),
[1] => Array ( "name" = "113" ),
[2] => Array ( "name" = "test 01" ),
[3] => Array ( "name" = "15000 tests" ),
[4] => Array ( "name" = "45" ),
[5] => Array ( "name" = "350" ),
[6] => Array ( "name" = "725" ),
[7] => Array ( "name" = "hello" )
}
SORT_STRING whould have returned me this :
Array ( // Numeric values are not correctly sorted
[0] => Array ( "name" = "113" ),
[1] => Array ( "name" = "12000" ),
[2] => Array ( "name" = "15000 tests" ),
[3] => Array ( "name" = "350" ),
[4] => Array ( "name" = "45" ),
[5] => Array ( "name" = "725" ),
[6] => Array ( "name" = "hello" ),
[7] => Array ( "name" = "test 01" )
}
SORT_NUMERIC would have returned me this :
Array ( // String values are not sorted, just in the same order
[0] => Array ( "name" = "test 01" ),
[1] => Array ( "name" = "hello" ),
[2] => Array ( "name" = "45" ),
[3] => Array ( "name" = "113" ),
[4] => Array ( "name" = "350" ),
[5] => Array ( "name" = "725" ),
[6] => Array ( "name" = "12000" ),
[7] => Array ( "name" = "15000 tests" ),
}
So I've made this hybrid code which combines the best of both worlds by merging content sorted either way according to the first caracter of the string:
<?php
/**
* Sorts an array according to a specified column
* Params : array $table
* string $colname
* bool $numeric
**/
function sort_col($table, $colname) {
$tn = $ts = $temp_num = $temp_str = array();
foreach ($table as $key => $row) {
if(is_numeric(substr($row[$colname], 0, 1))) {
$tn[$key] = $row[$colname];
$temp_num[$key] = $row;
}
else {
$ts[$key] = $row[$colname];
$temp_str[$key] = $row;
}
}
unset($table);
array_multisort($tn, SORT_ASC, SORT_NUMERIC, $temp_num);
array_multisort($ts, SORT_ASC, SORT_STRING, $temp_str);
return array_merge($temp_num, $temp_str);
}
?>
It would return something like this :
Array (
[2] => Array ( "name" = "45" ),
[3] => Array ( "name" = "113" ),
[4] => Array ( "name" = "350" ),
[5] => Array ( "name" = "725" ),
[6] => Array ( "name" = "12000" ),
[7] => Array ( "name" = "15000 tests" ),
[1] => Array ( "name" = "hello" ),
[0] => Array ( "name" = "test 01" ),
}
27-Nov-2008 04:36
<?php
/**
* Sort DB result
*
* @param array $data Result of sql query as associative array
*
* Rest of parameters are optional
* [, string $name [, mixed $name or $order [, mixed $name or $mode]]]
* $name string - column name i database table
* $order integer - sorting direction ascending (SORT_ASC) or descending (SORT_DESC)
* $mode integer - sorting mode (SORT_REGULAR, SORT_STRING, SORT_NUMERIC)
*
* <code>
* <?php
* // You can sort data by several columns e.g.
* $data = array();
* for ($i = 1; $i <= 10; $i++) {
* $data[] = array( 'id' => $i,
* 'first_name' => sprintf('first_name_%s', rand(1, 9)),
* 'last_name' => sprintf('last_name_%s', rand(1, 9)),
* 'date' => date('Y-m-d', rand(0, time()))
* );
* }
* $data = sortDbResult($data, 'date', SORT_DESC, SORT_NUMERIC, 'id');
* printf('<pre>%s</pre>', print_r($data, true));
* $data = sortDbResult($data, 'last_name', SORT_ASC, SORT_STRING, 'first_name', SORT_ASC, SORT_STRING);
* printf('<pre>%s</pre>', print_r($data, true));
* ?>
* </code>
*
* @return array $data - Sorted data
*/
function sortDbResult(array $data /*$name, $order, $mode*/) {
$_argList = func_get_args();
$_data = array_shift($_argList);
if (empty($_data)) {
return $_data;
}
$_max = count($_argList);
$_params = array();
$_cols = array();
$_rules = array();
for ($_i = 0; $_i < $_max; $_i += 3)
{
$_name = (string) $_argList[$_i];
if (!in_array($_name, array_keys(current($_data)))) {
continue;
}
if (!isset($_argList[($_i + 1)]) || is_string($_argList[($_i + 1)])) {
$_order = SORT_ASC;
$_mode = SORT_REGULAR;
$_i -= 2;
} else if (3 > $_argList[($_i + 1)]) {
$_order = SORT_ASC;
$_mode = $_argList[($_i + 1)];
$_i--;
} else {
$_order = $_argList[($_i + 1)] == SORT_ASC ? SORT_ASC : SORT_DESC;
if (!isset($_argList[($_i + 2)]) || is_string($_argList[($_i + 2)])) {
$_mode = SORT_REGULAR;
$_i--;
} else {
$_mode = $_argList[($_i + 2)];
}
}
$_mode = $_mode != SORT_NUMERIC
? $_argList[($_i + 2)] != SORT_STRING ? SORT_REGULAR : SORT_STRING
: SORT_NUMERIC;
$_rules[] = array('name' => $_name, 'order' => $_order, 'mode' => $_mode);
}
foreach ($_data as $_k => $_row) {
foreach ($_rules as $_rule) {
if (!isset($_cols[$_rule['name']])) {
$_cols[$_rule['name']] = array();
$_params[] = &$_cols[$_rule['name']];
$_params[] = $_rule['order'];
$_params[] = $_rule['mode'];
}
$_cols[$_rule['name']][$_k] = $_row[$_rule['name']];
}
}
$_params[] = &$_data;
call_user_func_array('array_multisort', $_params);
return $_data;
}
?>
10-Nov-2008 05:58
Since the manual doesn't specify so, I want to point out that the SORT_NUMERIC flag does also work correctly if the values are floating point numbers.
Just don't forget to also add the respective SORT_ASC or SORT_DESC flag :)
24-Oct-2008 03:47
I looked on some forms for an answer to this simple problem and couldn't find one so I came up with a solution that may help in some situations.
How do you sort an array by a field in that array and resolve numeric ties randomly?
Code:
<?php
foreach($list as $temp_list)
{
$sort_aux[] = ($temp_list['column_to_sort_by']+(rand(1, 9)/10));
}
array_multisort($sort_aux, SORT_NUMERIC, $list);
?>
Example:
$list[]=array('name'=>'Tom', 'score'=>3);
$list[]=array('name'=>'Sam', 'score'=>3);
$list[]=array('name'=>'Joey', 'score'=>1);
Explanation:
I took an existing example found above that shows how to sort an array by one of it's columns/fields.
I just added: "+(rand(1,9)/10)" To randomly add .1 through .9 to their score to resolve the tie. (Obviously this specific example only works if you're sorting by an integer... so you may need to modify it to suit your needs.)
Hope this helps someone.
19-Oct-2008 09:44
I would like to report a kind of confusion that arose with the message
Warning: Call-time pass-by-reference has been deprecated; If you would like to pass it by reference, modify the declaration of array_multisort(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file...
from a line like this:
array_multisort (&$keyarr, &$arr );// sort against this keys
This message is not easily switched off by changing the error reporting level because it's produced at parsinig time -- not execution time.
I think this message is misleading because the arguments are passed by reference ANYWAY in array_multisort.
Anybody encountering this message should know that nothing has to be done, except deleting the ampersands (&).
I was tricked by this message because of couse I wanted to have the *sorted* array back. And couldn't find the ini file nor the declaration of array_multisort.
I think in this description of array_multisort the call by reference should be listed in the definition.
Hope this helps someone
19-Aug-2008 12:53
There have to be two corrections to the php_multisort($data,$keys)
// Sort Expression
$i=0;
$sort=''; //here
foreach ($keys as $k){
if($i>0){$sort.=',';}
$sort.='$cols[\''.$k['key'].'\']'; //and here
if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
$i++;
}
11-May-2008 06:16
I was requiring a PHP function a sort my array data as part of an SQL interpreter for PHP arrays. This is the code I came up with. and works wonderfully.
I hope this helps somebody. If anyone uses this, let me know what you think, if there are any problems with it...
<?
## ##
## PHPMultiSort ##
## ##
// Takes:
// $data, multidim array
// $keys, array(array(key=>col1, sort=>desc), array(key=>col2, type=>numeric))
function php_multisort($data,$keys){
// List As Columns
foreach ($data as $key => $row) {
foreach ($keys as $k){
$cols[$k['key']][$key] = $row[$k['key']];
}
}
// List original keys
$idkeys=array_keys($data);
// Sort Expression
$i=0;
foreach ($keys as $k){
if($i>0){$sort.=',';}
$sort.='$cols['.$k['key'].']';
if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
$i++;
}
$sort.=',$idkeys';
// Sort Funct
$sort='array_multisort('.$sort.');';
eval($sort);
// Rebuild Full Array
foreach($idkeys as $idkey){
$result[$idkey]=$data[$idkey];
}
return $result;
}
###############
// Example Data
$_DATA['table1'][] = array("name" => "Sebastian", "age" => 18, "male" => true);
$_DATA['table1'][] = array("name" => "Lawrence", "age" => 16, "male" => true);
$_DATA['table1'][] = array("name" => "Olivia", "age" => 10, "male" => false);
$_DATA['table1'][] = array("name" => "Dad", "age" => 50, "male" => true);
$_DATA['table1'][] = array("name" => "Mum", "age" => 40, "male" => false);
$_DATA['table1'][] = array("name" => "Sebastian", "age" => 56, "male" => true);
$_DATA['table1'][] = array("name" => "Lawrence", "age" => 19, "male" => true);
$_DATA['table1'][] = array("name" => "Olivia", "age" => 24, "male" => false);
$_DATA['table1'][] = array("name" => "Dad", "age" => 10, "male" => true);
$_DATA['table1'][] = array("name" => "Mum", "age" => 70, "male" => false);
###############
$res=php_multisort($_DATA['table1'], array(array('key'=>'name'),array('key'=>'age','sort'=>'desc')))
var_dump($res);
/*
array(10) {
[8]=>
array(3) {
["name"]=>
string(3) "Dad"
["age"]=>
int(10)
["male"]=>
bool(true)
}
[3]=>
array(3) {
["name"]=>
string(3) "Dad"
["age"]=>
int(50)
["male"]=>
bool(true)
}
[1]=>
array(3) {
["name"]=>
string(8) "Lawrence"
["age"]=>
int(16)
["male"]=>
bool(true)
}
[6]=>
array(3) {
["name"]=>
string(8...
*/
?>
23-Apr-2008 07:02
To sort the array returned e.g. by oci_fetch_all you must divide it in seperate arrays.
Example:
<?php
$rows=oci_fetch_all($stmt,$results);
?>
now you have several arrays each named by the key name in the sql result.
E.g. array of names, array of streets, array of towns.
To sort the result by e.g. towns you would do the following:
<?php
array_multisort($results[towns],$results[names],$results[streets]);
?>
Done.
To display the result sorted by towns you could use this:
<?php
print_r(array("names"=>$results[names],"streets"=>$results[streets],
"towns"=>$result[towns]));
?>
10-Apr-2008 08:50
@ scott at bartoncomputer dot com
You could also reference the array (if you wanted the original array in the object sorted):
array_multisort($position, SORT_DESC, &$clsVar->data);
Regards, Chr.
25-Feb-2008 04:02
I believe this should read:
foreach($firstarray as $sortarray){
$column[] = $sortarray['email'];
}
//sort arrays after loop
array_multisort($column, SORT_ASC, $firstarray);
Otherwise you will get an array is inconsistent err because $column array won't equal $firstarray until the loop completes.
It was the only way I got it to work, then it was fine. If I am wrong please post a correction.
30-Nov-2007 03:49
To sort a nested array by column (key/index):
Example: two entries in the nested array:
firstarray[0]['adres'] = "adres1"
firstarray[0]['email'] = "email2"
firstarray[1]['adres'] = "adres2"
firstarray[1]['email'] = "email1"
-----------------------------------------
Without code: output would put adres1/email2 on top
-----------------------------------------
foreach($firstarray as $sortarray)
{
$column[] = $sortarray['email'];
array_multisort($column, SORT_ASC, $firstarray);
}
-----------------------------------------
With code: output would put adres2/email1 on top
04-May-2007 02:18
I didn't see this noted anywhere, so I figured I'd put in a little comment regarding arrays located inside classes. For instance:
class abc
{
var $data;
}
The following code does not act as expected:
$clsVar =& new abc();
foreach ($clsVar->data as $key => $row)
{
$position[$key] = $key;
}
array_multisort($position, SORT_DESC, $clsVar->data);
While I realize this could much easily be acheived using ksort(), this is merely a much more simple example of this behaviour. The exerpt above comes from a much more complicated sort using multi-scripted arrays.
Anyway the only way I could find to get around the behaviour of multisort not sorting the referenced class-array was to make a copy of it as below:
$clsVar =& new abc();
$newData = $clsVar->data;
foreach ($newData as $key => $row)
{
$position[$key] = $key;
}
array_multisort($position, SORT_DESC, $newData);
Now newData will contain the sorted array as expected.
Hopefully this helps someone else!
<?php
$strDeger = 'aaaa|bbbb|cccc';
$arrBol = explode('|',$strDeger);
array_multisort($arrBol, 