note 104714 added to function.uasort

From: Date: Sat, 02 Jul 2011 11:44:59 +0000
Subject: note 104714 added to function.uasort
Groups: php.notes 
Request: Send a blank email to php-notes+get-181161@lists.php.net to get a copy of this message
In case you need to sort an associative array by one of its keys, this function might be useful: <?php function sortByOneKey(array $array, $key, $asc = true) { $result = array(); $values = array(); foreach ($array as $id => $value) { $values[$id] = isset($value[$key]) ? $value[$key] : ''; } if ($asc) { asort($values); } else { arsort($values); } foreach ($values as $key => $value) { $result[$key] = $array[$key]; } return $result; } ?> Consider the following example: <?php $users = array( 1 => array('name' => 'John', 'age' => 35), 2 => array('name' => 'Alice', 'age' => 23), 3 => array('name' => 'Bob', 'age' => 26) ); $sortedByNameAsc = sortByOneKey($users, 'name'); $sortedByNameDesc = sortByOneKey($users, 'name', false); echo "Sorted by Name in ascending order: "; echo "<pre>" . print_r($sortedByNameAsc, true) . "</pre>"; echo "<br /><br />Sorted by Name in descending order: "; echo "<pre>" . print_r($sortedByNameDesc, true) . "</pre>"; ?> The output will be the following: Sorted by Name in ascending order: Array ( [2] => Array ( [name] => Alice [age] => 23 ) [3] => Array ( [name] => Bob [age] => 26 ) [1] => Array ( [name] => John [age] => 35 ) ) Sorted by Name in descending order: Array ( [1] => Array ( [name] => John [age] => 35 ) [3] => Array ( [name] => Bob [age] => 26 ) [2] => Array ( [name] => Alice [age] => 23 ) ) ---- Server IP: 69.147.83.197 Probable Submitter: 93.75.69.183 ---- Manual Page -- http://www.php.net/manual/en/function.uasort.php Edit -- https://master.php.net/note/edit/104714 Del: integrated -- https://master.php.net/note/delete/104714/integrated Del: useless -- https://master.php.net/note/delete/104714/useless Del: bad code -- https://master.php.net/note/delete/104714/bad+code Del: spam -- https://master.php.net/note/delete/104714/spam Del: non-english -- https://master.php.net/note/delete/104714/non-english Del: in docs -- https://master.php.net/note/delete/104714/in+docs Del: other reasons-- https://master.php.net/note/delete/104714 Reject -- https://master.php.net/note/reject/104714 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#181161) next »