note 88894 added to function.usort

From: Date: Thu, 12 Feb 2009 12:29:08 +0000
Subject: note 88894 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-150567@lists.php.net to get a copy of this message
I often need to order arrays by one dimension, therefore, I implemented a generic function, called "g_arr_dimsort": <? function arr_dimsort_cmp($a,$b) /* * Compare function used when sorting arrays. */ { global $G_ARR_STYPE, $G_ARR_SDIM; /* -- Sort numbers? */ if ($G_ARR_STYPE == 'NUMBER') { if ((float)$a[$G_ARR_SDIM] == (float)$b[$G_ARR_SDIM]) return 0; return (floatval($a[$G_ARR_SDIM]) > floatval($b[$G_ARR_SDIM])) ? 1: -1; } /* -- Sort strings? */ if ($G_ARR_STYPE == 'STRING') return strcmp($a[$G_ARR_SDIM],$b[$G_ARR_SDIM]); /* -- First time: get the right data type */ $G_ARR_STYPE = is_string($a[$G_ARR_SDIM])? 'STRING' : 'NUMBER'; return arr_dimsort_cmp($a,$b); } function g_arr_dimsort(&$arr,$dim,$type = '',$keepkey = false) /* * Sort an array by a given dimension */ { global $G_ARR_SDIM, $G_ARR_STYPE; $G_ARR_SDIM = $dim; $G_ARR_STYPE = $type; if ($keepkey) uasort(&$arr,'arr_dimsort_cmp'); else usort(&$arr,'arr_dimsort_cmp'); } /* -- Testing it: */ $arr[] = array('Fruit' => 'Orange','Stock' => 10, 'Price'=> 10.2); $arr[] = array('Fruit' => 'Lemon' ,'Stock' => 100,'Price'=> 5.36); $arr[] = array('Fruit' => 'Apple' ,'Stock' => 20,'Price'=> 11.1); echo "Sort by Fruit\n"; g_arr_dimsort(&$arr,'Fruit'); print_r($arr); echo "Sort by Stock\n"; g_arr_dimsort(&$arr,'Stock','NUMBER'); print_r($arr); echo "Sort by Fruit and keep keys\n"; g_arr_dimsort(&$arr,'Fruit','',true); print_r($arr); echo "Sort by Price\n"; g_arr_dimsort(&$arr,'Price'); print_r($arr); ?> ---- Server IP: 64.71.164.2 Probable Submitter: 194.65.5.228 ---- Manual Page -- http://www.php.net/manual/en/function.usort.php Edit -- https://master.php.net/note/edit/88894 Del: integrated -- https://master.php.net/note/delete/88894/integrated Del: useless -- https://master.php.net/note/delete/88894/useless Del: bad code -- https://master.php.net/note/delete/88894/bad+code Del: spam -- https://master.php.net/note/delete/88894/spam Del: non-english -- https://master.php.net/note/delete/88894/non-english Del: in docs -- https://master.php.net/note/delete/88894/in+docs Del: other reasons-- https://master.php.net/note/delete/88894 Reject -- https://master.php.net/note/reject/88894 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#150567) next »