note 91638 added to function.array-multisort

From: Date: Sat, 20 Jun 2009 19:16:54 +0000
Subject: note 91638 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-157183@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 92.48.74.199 Probable Submitter: 83.31.234.112 ---- Manual Page -- http://www.php.net/manual/en/function.array-multisort.php Edit -- https://master.php.net/note/edit/91638 Del: integrated -- https://master.php.net/note/delete/91638/integrated Del: useless -- https://master.php.net/note/delete/91638/useless Del: bad code -- https://master.php.net/note/delete/91638/bad+code Del: spam -- https://master.php.net/note/delete/91638/spam Del: non-english -- https://master.php.net/note/delete/91638/non-english Del: in docs -- https://master.php.net/note/delete/91638/in+docs Del: other reasons-- https://master.php.net/note/delete/91638 Reject -- https://master.php.net/note/reject/91638 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#157183) next »