note 74461 added to function.sort

From: Date: Thu, 12 Apr 2007 12:43:36 +0000
Subject: note 74461 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-125331@lists.php.net to get a copy of this message
This is a function to sort any 2D array by a specified sub array key, either ascending or descending. It is useful for sorting query results from a database by a particular field after the query has been returned It recreates the array as a hash to use ksort() then back again By default it will sort ascending but if you specify $reverse as true it will return the records sorted descending By default the array is re created as an indexed array but if you set $keep_key to true it maintain the keys (useful for associative arrays) <?php //function record_sort(Mixed Array &$records, String $field [, [Boolean $reverse=false], [Boolean $keep_key=false]]) function record_sort(&$records, $field, $reverse=false, $keep_key=false) { $hash = array(); foreach($records as $key => &$record) { $hash[$record[$field]][$key] = $record; unset($records[$key]); } ($reverse)? krsort($hash) : ksort($hash); $records = array(); foreach($hash as $key => &$field) { foreach($field as $key2 => &$record) { ($keep_key)? $records[$key2] = $record : $records []= $record; unset($field[$key2]); } unset($hash[$key]); } unset($hash); } // Example below $airports = array ( array( "code" => "LHR", "name" => "Heathrow" ), array( "code" => "LGW", "name" => "Gatwick" ), ); printf("Before: <pre>%s</pre>", print_r($airports, true)); record_sort($airports, "name"); printf("After: <pre>%s</pre>", print_r($airports, true)); ?> Example Outputs: Before: Array ( [0] => Array ( [code] => LHR, [name] => Heathrow ) [1] => Array ( [code] => LGW, [name] => Gatwick ) ) After: Array ( [0] => Array ( [code] => LGW, [name] => Gatwick ) [1] => Array ( [code] => LHR, [name] => Heathrow ) ) ---- Server IP: 194.145.210.3 Probable Submitter: 80.194.36.8 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/74461 Del: integrated -- https://master.php.net/note/delete/74461/integrated Del: useless -- https://master.php.net/note/delete/74461/useless Del: bad code -- https://master.php.net/note/delete/74461/bad+code Del: spam -- https://master.php.net/note/delete/74461/spam Del: non-english -- https://master.php.net/note/delete/74461/non-english Del: in docs -- https://master.php.net/note/delete/74461/in+docs Del: other reasons-- https://master.php.net/note/delete/74461 Reject -- https://master.php.net/note/reject/74461 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#125331) next »