note 35190 added to function.natsort
| From: | justin at rack1 dot php dot net | Date: | Fri, 22 Aug 2003 15:10:49 +0000 |
| Subject: | note 35190 added to function.natsort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-54880@lists.php.net to get a copy of this message | ||
One of the things I've needed to do lately is apply natural sorting to a complex array, e.g.:
Array
(
[0] => Array
(
[ID] = 4
[name] = Fred
)
[1] => Array
(
[ID] = 6
[name] = Bob
)
)
where I want to sort the parent array by the child's name. I couldn't see a way of doing
this using array_walk, so I've written a simple function to do it. Hopefully someone will find
this useful:
/**
* @return Returns the array sorted as required
* @param $aryData Array containing data to sort
* @param $strIndex Name of column to use as an index
* @param $strSortBy Column to sort the array by
* @param $strSortType String containing either asc or desc [default to asc]
* @desc Naturally sorts an array using by the column $strSortBy
*/
function array_natsort($aryData, $strIndex, $strSortBy, $strSortType=false)
{
// if the parameters are invalid
if (!is_array($aryData) || !$strIndex || !$strSortBy)
// return the array
return $aryData;
// create our temporary arrays
$arySort = $aryResult = array();
// loop through the array
foreach ($aryData as $aryRow)
// set up the value in the array
$arySort[$aryRow[$strIndex]] = $aryRow[$strSortBy];
// apply the natural sort
natsort($arySort);
// if the sort type is descending
if ($strSortType=="desc")
// reverse the array
arsort($arySort);
// loop through the sorted and original data
foreach ($arySort as $arySortKey => $arySorted)
foreach ($aryData as $aryOriginal)
// if the key matches
if ($aryOriginal[$strIndex]==$arySortKey)
// add it to the output array
array_push($aryResult, $aryOriginal);
// return the return
return $aryResult;
}
----
Manual Page -- http://www.php.net/manual/en/function.natsort.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35190
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35190&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35190&report=yes