note 81902 added to language.types.array
| From: | rama dot devi at gmail dot com | Date: | Tue, 18 Mar 2008 21:52:06 +0000 |
| Subject: | note 81902 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-137184@lists.php.net to get a copy of this message | ||
Sorting double dimensional arrays by a specified key bothe for Strings and for integers:
Ex:
$personDetails = array( array("firstName" => "Nancy", "lastName"
=> "Grace", "age" => 22), array("firstName" =>
"Andy", "lastName" => "Peter", "age" => 28),
array("firstName" => "Jim", "lastName" =>
"Gary", "age" => 25), array("firstName" => "Lary",
"lastName" => "James", "age" => 28),
array("firstName" => "Peter", "lastName" => "David",
"age" => 17), array("firstName" => "Raj", "lastName"
=> "King", "age" => 9),
array("firstName" => "John", "lastName" =>
"Baxter","age" => 35) );
//To sort the array by firstName:-
function sortFirstName($p1, $p2) {
return strnatcmp($p1['firstName'], $p2['firstName']);
}
usort($personDetails, 'sortFirstName');
//To sort by an integer Field
function sortByInteger(&$personDetails, $field) {
$sort = "return strnatcmp(\$p1['$field'], \$p2['$field']);";
usort($personDetails, create_function('$p1,$p2', $sort));
return $personDetails;
}
$personDetails = sortByInteger($personDetails, 'age');
//To sort the array in Descending order by a key, It can be done by adding "-" sign before
strnatcmp() function.
I hope this helps
----
Server IP: 69.147.83.197
Probable Submitter: 66.248.222.34
----
Manual Page -- http://www.php.net/manual/en/language.types.array.php
Edit -- https://master.php.net/note/edit/81902
Del: integrated -- https://master.php.net/note/delete/81902/integrated
Del: useless -- https://master.php.net/note/delete/81902/useless
Del: bad code -- https://master.php.net/note/delete/81902/bad+code
Del: spam -- https://master.php.net/note/delete/81902/spam
Del: non-english -- https://master.php.net/note/delete/81902/non-english
Del: in docs -- https://master.php.net/note/delete/81902/in+docs
Del: other reasons-- https://master.php.net/note/delete/81902
Reject -- https://master.php.net/note/reject/81902
Search -- https://master.php.net/manage/user-notes.php