note 114076 added to function.array-multisort
| From: | RobertC | Date: | Thu, 09 Jan 2014 12:11:09 +0000 |
| Subject: | note 114076 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198169@lists.php.net to get a copy of this message | ||
Hi,
I would like to see the next code snippet to be added to http://nl3.php.net/array_multisort
Purpose: Sort a 2-dimensional array on some key(s)
Advantage of function:
- uses PHP's array_multisort function for sorting;
- it prepares the arrays (needed by array_multisort) for you;
- allows the sort criteria be passed as a separate array (It is possible to use sort order and
flags.);
- easy to set/overwrite the way strings are sorted (case insensitive instead of case sensitive,
which is PHP's default way of sorting);
- performs excellent
function MultiSort($data, $sortCriteria, $caseInSensitive = true)
{
if( !is_array($data) || !is_array($sortCriteria))
return false;
$args = array();
$i = 0;
foreach($sortCriteria as $sortColumn => $sortAttributes)
{
$colList = array();
foreach ($data as $key => $row)
{
$convertToLower = $caseInSensitive && (in_array(SORT_STRING, $sortAttributes) ||
in_array(SORT_REGULAR, $sortAttributes));
$rowData = $convertToLower ? strtolower($row[$sortColumn]) : $row[$sortColumn];
$colLists[$sortColumn][$key] = $rowData;
}
$args[] = &$colLists[$sortColumn];
foreach($sortAttributes as $sortAttribute)
{
$tmp[$i] = $sortAttribute;
$args[] = &$tmp[$i];
$i++;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return end($args);
}
Usage:
//Fill an array with random test data
define('MAX_ITEMS', 15);
define('MAX_VAL', 20);
for($i=0; $i < MAX_ITEMS; $i++)
$data[] = array('field1' => rand(1, MAX_VAL), 'field2' => rand(1,
MAX_VAL), 'field3' => rand(1, MAX_VAL) );
//Set the sort criteria (add as many fields as you want)
$sortCriteria =
array('field1' => array(SORT_DESC, SORT_NUMERIC),
'field3' => array(SORT_DESC, SORT_NUMERIC)
);
//Call it like this:
$sortedData = MultiSort($data, $sortCriteria, true);
----
Server IP: 91.199.167.223
Probable Submitter: 193.200.140.75
----
Manual Page -- http://php.net/manual/en/function.array-multisort.php
Edit -- https://master.php.net/note/edit/114076
Del: integrated -- https://master.php.net/note/delete/114076/integrated
Del: useless -- https://master.php.net/note/delete/114076/useless
Del: bad code -- https://master.php.net/note/delete/114076/bad+code
Del: spam -- https://master.php.net/note/delete/114076/spam
Del: non-english -- https://master.php.net/note/delete/114076/non-english
Del: in docs -- https://master.php.net/note/delete/114076/in+docs
Del: other reasons-- https://master.php.net/note/delete/114076
Reject -- https://master.php.net/note/reject/114076
Search -- https://master.php.net/manage/user-notes.php