note 95694 added to function.sort

From: Date: Sat, 16 Jan 2010 12:49:20 +0000
Subject: note 95694 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-165024@lists.php.net to get a copy of this message
PHP offers dozens of functions for sorting arrays, but unfortunately non of this functions support sorting by sub-key's value out of the box. It's very useful when you want to sort the result of a query by an specific column. Questions/Suggestions?! : send your comments here http://sina.salek.ws/node/1308 Sample : <?php $users=array( array( 'username'=>'Ashkan1', 'age'=>20, ), array( 'username'=>'Ashkan2', 'age'=>35, ), array( 'username'=>'Ashkan3', 'age'=>18, ), ); $users=arraySortTwoDimByValueKey($users,'age','asc'); /* Result : array ( array( 'username'=>'Ashkan3', 'age'=>18, ), array( 'username'=>'Ashkan1', 'age'=>20, ), array( 'username'=>'Ashkan2', 'age'=>35, ), ) */ ?> And the function : <?php /** * Sorting two dimensional array by sub-key's value * @author sina.salek.ws * @param $array array * @param $by string //Sub-key name * @param $type string //asc,desc * @return array */ function arraySortTwoDimByValueKey($array,$by,$type='asc') { $sortField=&$by; $multArray=&$array; $tmpKey=''; $ResArray=array(); $maIndex=array_keys($multArray); $maSize=count($multArray)-1; for($i=0; $i < $maSize ; $i++) { $minElement=$i; $tempMin=$multArray[$maIndex[$i]][$sortField]; $tmpKey=$maIndex[$i]; for ($j=$i+1; $j <= $maSize; $j++) { if ($multArray[$maIndex[$j]][$sortField] < $tempMin ) { $minElement=$j; $tmpKey=$maIndex[$j]; $tempMin=$multArray[$maIndex[$j]][$sortField]; } } $maIndex[$minElement]=$maIndex[$i]; $maIndex[$i]=$tmpKey; } if ($type=='asc') { for ($j=0;$j<=$maSize;$j++) { $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]]; } } else { for ($j=$maSize;$j>=0;$j--) { $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]]; } } return $ResArray; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 84.47.225.66 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/95694 Del: integrated -- https://master.php.net/note/delete/95694/integrated Del: useless -- https://master.php.net/note/delete/95694/useless Del: bad code -- https://master.php.net/note/delete/95694/bad+code Del: spam -- https://master.php.net/note/delete/95694/spam Del: non-english -- https://master.php.net/note/delete/95694/non-english Del: in docs -- https://master.php.net/note/delete/95694/in+docs Del: other reasons-- https://master.php.net/note/delete/95694 Reject -- https://master.php.net/note/reject/95694 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#165024) next »