note 71318 added to function.asort

From: Date: Wed, 22 Nov 2006 11:35:16 +0000
Subject: note 71318 added to function.asort
Groups: php.notes 
Request: Send a blank email to php-notes+get-119975@lists.php.net to get a copy of this message
This is a function to sort an indexed 2D array by a specified sub array key, either ascending or descending. It is usefull for sorting query results from a database by a particular field after the query has been returned This function can be quite greedy. 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 <?php function record_sort($records, $field, $reverse=false) { $hash = array(); foreach($records as $record) { $hash[$record[$field]] = $record; } ($reverse)? krsort($hash) : ksort($hash); $records = array(); foreach($hash as $record) { $records []= $record; } return $records; } // Example below $airports = array ( array( "code" => "LHR", "name" => "Heathrow" ), array( "code" => "LGW", "name" => "Gatwick" ), ); printf("Before: <pre>%s</pre>", print_r($airports, true)); $airports = 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: 85.116.0.130 Probable Submitter: 80.194.36.8 ---- Manual Page -- http://www.php.net/manual/en/function.asort.php Edit -- https://master.php.net/note/edit/71318 Del: integrated -- https://master.php.net/note/delete/71318/integrated Del: useless -- https://master.php.net/note/delete/71318/useless Del: bad code -- https://master.php.net/note/delete/71318/bad+code Del: spam -- https://master.php.net/note/delete/71318/spam Del: non-english -- https://master.php.net/note/delete/71318/non-english Del: in docs -- https://master.php.net/note/delete/71318/in+docs Del: other reasons-- https://master.php.net/note/delete/71318 Reject -- https://master.php.net/note/reject/71318 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#119975) next »