note 96704 added to function.sort

From: Date: Fri, 12 Mar 2010 06:10:18 +0000
Subject: note 96704 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-166944@lists.php.net to get a copy of this message
I could never find a way to sort multidimensional arrays with 5+ keys while maintaining the data structure, but here it is: (you can add an infinite number of keys, but it has to be added manually :\ ) <?php $array[0]['name'] = 'Chris'; $array[0]['phone'] = '3971095'; $array[0]['year'] = '1978'; $array[0]['address'] = 'Street 1'; $array[1]['name'] = 'Breanne'; $array[1]['phone'] = '3766350'; $array[1]['year'] = '1990'; $array[1]['address'] = 'Street 2'; $array[2]['name'] = 'Dusty'; $array[2]['phone'] = '1541120'; $array[2]['year'] = '1982'; $array[2]['address'] = 'Street 3'; function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL, $key5=NULL, $key6=NULL){ // sort by ? foreach ($array as $pos => $val) $tmp_array[$pos] = $val[$sort_by]; asort($tmp_array); // display however you want foreach ($tmp_array as $pos => $val){ $return_array[$pos][$sort_by] = $array[$pos][$sort_by]; $return_array[$pos][$key1] = $array[$pos][$key1]; if (isset($key2)){ $return_array[$pos][$key2] = $array[$pos][$key2]; } if (isset($key3)){ $return_array[$pos][$key3] = $array[$pos][$key3]; } if (isset($key4)){ $return_array[$pos][$key4] = $array[$pos][$key4]; } if (isset($key5)){ $return_array[$pos][$key5] = $array[$pos][$key5]; } if (isset($key6)){ $return_array[$pos][$key6] = $array[$pos][$key6]; } } return $return_array; } //usage (only enter the keys you want sorted): $sorted = multisort($array,'year','name','phone','address'); print_r($sorted); //output: Array ( [0] => Array ( [year] => 1978 [name] => Chris [phone] => 3971095 [address] => Street 1 ) [2] => Array ( [year] => 1982 [name] => Dusty [phone] => 1541120 [address] => Street 3 ) [1] => Array ( [year] => 1990 [name] => Breanne [phone] => 3766350 [address] => Street 2 ) ) ---- Server IP: 64.71.164.2 Probable Submitter: 67.183.163.170 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/96704 Del: integrated -- https://master.php.net/note/delete/96704/integrated Del: useless -- https://master.php.net/note/delete/96704/useless Del: bad code -- https://master.php.net/note/delete/96704/bad+code Del: spam -- https://master.php.net/note/delete/96704/spam Del: non-english -- https://master.php.net/note/delete/96704/non-english Del: in docs -- https://master.php.net/note/delete/96704/in+docs Del: other reasons-- https://master.php.net/note/delete/96704 Reject -- https://master.php.net/note/reject/96704 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166944) next »