note 80798 added to function.asort

From: Date: Thu, 31 Jan 2008 23:23:55 +0000
Subject: note 80798 added to function.asort
Groups: php.notes 
Request: Send a blank email to php-notes+get-135681@lists.php.net to get a copy of this message
For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each. <?php function aksort(&$array,$valrev=false,$keyrev=false) { if ($valrev) { arsort($array); } else { asort($array); } $vals = array_count_values($array); $i = 0; foreach ($vals AS $val=>$num) { $first = array_splice($array,0,$i); $tmp = array_splice($array,0,$num); if ($keyrev) { krsort($tmp); } else { ksort($tmp); } $array = array_merge($first,$tmp,$array); unset($tmp); $i = $num; } } // Example $tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1); // Standard asort asort($tmp); print_r($tmp); // Sort value ASC, key ASC aksort($tmp); print_r($tmp); // Sort value DESC, key ASC aksort($tmp,true); print_r($tmp); // Sort value DESC, key DESC aksort($tmp,true,true); print_r($tmp); // Results Array ( [pe] => 1 [ca] => 1 [ce] => 1 [cb] => 2 [pa] => 2 ) Array ( [ca] => 1 [ce] => 1 [pe] => 1 [cb] => 2 [pa] => 2 ) Array ( [cb] => 2 [pa] => 2 [ca] => 1 [ce] => 1 [pe] => 1 ) Array ( [pa] => 2 [cb] => 2 [pe] => 1 [ce] => 1 [ca] => 1 ) ---- Server IP: 208.69.120.35 Probable Submitter: 65.106.115.18 ---- Manual Page -- http://www.php.net/manual/en/function.asort.php Edit -- https://master.php.net/note/edit/80798 Del: integrated -- https://master.php.net/note/delete/80798/integrated Del: useless -- https://master.php.net/note/delete/80798/useless Del: bad code -- https://master.php.net/note/delete/80798/bad+code Del: spam -- https://master.php.net/note/delete/80798/spam Del: non-english -- https://master.php.net/note/delete/80798/non-english Del: in docs -- https://master.php.net/note/delete/80798/in+docs Del: other reasons-- https://master.php.net/note/delete/80798 Reject -- https://master.php.net/note/reject/80798 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#135681) next »