note 91645 deleted from function.array-multisort by cmb
| From: | cmb@php.net | Date: | Sun, 24 Nov 2019 09:07:00 +0000 |
| Subject: | note 91645 deleted from function.array-multisort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213232@lists.php.net to get a copy of this message | ||
Note Submitter: cagret at gmail dot com
----
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;
}
?>