note 73498 added to function.array-multisort

From: Date: Mon, 26 Feb 2007 16:27:20 +0000
Subject: note 73498 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-123900@lists.php.net to get a copy of this message
This is my solution for a dynamic multisort, using POST values. This doesn't account for a need to sort by multiple columns at once, but could be modified for that purpose. <?php /** * @desc You really should validate the posted sort direction against a list of valid possibilities. * Options are SORT_ASC, SORT_DESC, etc, as shown in the documentation for array_multisort */ $sort['direction'] = $_POST['sort_direction'] ? $_POST['sort_direction'] : 'SORT_ASC'; $sort['field'] = $_POST['sort_field'] ? $_POST['sort_field'] : 'value'; $array_to_sort = array(); $array_to_sort['TestCase1'] = array('name'=>'Test1','value'=>'218'); $array_to_sort['TestCase2'] = array('name'=>'Test2','value'=>'10'); $array_to_sort['TestCase3'] = array('name'=>'Test3','value'=>'64'); /** * @desc Build columns using the values, for sorting in php */ $sort_arr = array(); foreach($array_to_sort AS $uniqid => $row){ foreach($row AS $key=>$value){ $sort_arr[$key][$uniqid] = $value; } } print '<b>Before sorting</b>: <br> <pre>'; print_r($array_to_sort); print '</pre>'; if($sort['direction']){ array_multisort($sort_arr[$sort['field']], constant($sort['direction']), $array_to_sort); } print '<b>After sorting</b>: <br> <pre>'; print_r($array_to_sort); print '</pre>'; ?> This example prints out: Before sorting: Array ( [TestCase1] => Array ( [name] => Test1 [value] => 218 ) [TestCase2] => Array ( [name] => Test2 [value] => 10 ) [TestCase3] => Array ( [name] => Test3 [value] => 64 ) ) After sorting: Array ( [TestCase2] => Array ( [name] => Test2 [value] => 10 ) [TestCase3] => Array ( [name] => Test3 [value] => 64 ) [TestCase1] => Array ( [name] => Test1 [value] => 218 ) ) ---- Server IP: 216.194.113.175 Probable Submitter: 216.48.9.145 ---- Manual Page -- http://www.php.net/manual/en/function.array-multisort.php Edit -- https://master.php.net/note/edit/73498 Del: integrated -- https://master.php.net/note/delete/73498/integrated Del: useless -- https://master.php.net/note/delete/73498/useless Del: bad code -- https://master.php.net/note/delete/73498/bad+code Del: spam -- https://master.php.net/note/delete/73498/spam Del: non-english -- https://master.php.net/note/delete/73498/non-english Del: in docs -- https://master.php.net/note/delete/73498/in+docs Del: other reasons-- https://master.php.net/note/delete/73498 Reject -- https://master.php.net/note/reject/73498 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#123900) next »