note 96752 added to function.sort

From: Date: Sun, 14 Mar 2010 15:46:11 +0000
Subject: note 96752 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-167012@lists.php.net to get a copy of this message
Use eval() with array_multisort() to sort multiple columns: <?php function multisort($array, $sort_by) { foreach ($array as $key => $value) { $evalstring = ''; foreach ($sort_by as $sort_field) { $tmp[$sort_field][$key] = $value[$sort_field]; $evalstring .= '$tmp[\'' . $sort_field . '\'], '; } } $evalstring .= '$array'; $evalstring = 'array_multisort(' . $evalstring . ');'; eval($evalstring); return $array; } $test = array( array( 'a' => '1', 'b' => '3'), array( 'a' => '2', 'b' => '1'), array( 'a' => '1', 'b' => '1')); echo 'Unsorted: '; print_r($test); $result = multisort( $test , array('a','b') ); echo 'Sorted: '; print_r($result); ?> Result: Unsorted: Array ( [0] => Array ( [a] => 1 [b] => 3 ) [1] => Array ( [a] => 2 [b] => 1 ) [2] => Array ( [a] => 1 [b] => 1 ) ) Sorted: Array ( [0] => Array ( [a] => 1 [b] => 1 ) [1] => Array ( [a] => 1 [b] => 3 ) [2] => Array ( [a] => 2 [b] => 1 ) ) ---- Server IP: 85.214.154.209 Probable Submitter: 92.228.149.63 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/96752 Del: integrated -- https://master.php.net/note/delete/96752/integrated Del: useless -- https://master.php.net/note/delete/96752/useless Del: bad code -- https://master.php.net/note/delete/96752/bad+code Del: spam -- https://master.php.net/note/delete/96752/spam Del: non-english -- https://master.php.net/note/delete/96752/non-english Del: in docs -- https://master.php.net/note/delete/96752/in+docs Del: other reasons-- https://master.php.net/note/delete/96752 Reject -- https://master.php.net/note/reject/96752 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#167012) next »