note 73919 added to function.sort
| From: | y5atyellow5dotus at osu1 dot php dot net | Date: | Thu, 15 Mar 2007 14:52:50 +0000 |
| Subject: | note 73919 added to function.sort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-124483@lists.php.net to get a copy of this message | ||
An improvement on the very nice code submitted by alex [at] vkpb [dot] com. This will preserve the
keys if the array is numeric:
function SortDataSet($aArray, $sField, $bDescending = false)
{
$bIsNumeric = IsNumeric($aArray);
$aKeys = array_keys($aArray);
$nSize = sizeof($aArray);
for ($nIndex = 0; $nIndex < $nSize - 1; $nIndex++)
{
$nMinIndex = $nIndex;
$objMinValue = $aArray[$aKeys[$nIndex]][$sField];
$sKey = $aKeys[$nIndex];
for ($nSortIndex = $nIndex + 1; $nSortIndex < $nSize; ++$nSortIndex)
{
if ($aArray[$aKeys[$nSortIndex]][$sField] < $objMinValue)
{
$nMinIndex = $nSortIndex;
$sKey = $aKeys[$nSortIndex];
$objMinValue = $aArray[$aKeys[$nSortIndex]][$sField];
}
}
$aKeys[$nMinIndex] = $aKeys[$nIndex];
$aKeys[$nIndex] = $sKey;
}
$aReturn = array();
for($nSortIndex = 0; $nSortIndex < $nSize; ++$nSortIndex)
{
$nIndex = $bDescending ? $nSize - $nSortIndex - 1: $nSortIndex;
$aReturn[$aKeys[$nIndex]] = $aArray[$aKeys[$nIndex]];
}
return $bIsNumeric ? array_values($aReturn) : $aReturn;
}
function IsNumeric($aArray)
{
$aKeys = array_keys($aArray);
for ($nIndex = 0; $nIndex < sizeof($aKeys); $nIndex++)
{
if (!is_int($aKeys[$nIndex]) || ($aKeys[$nIndex] != $nIndex))
{
return false;
}
}
return true;
}
----
Server IP: 64.71.164.2
Probable Submitter: 64.179.48.194
----
Manual Page -- http://www.php.net/manual/en/function.sort.php
Edit -- https://master.php.net/note/edit/73919
Del: integrated -- https://master.php.net/note/delete/73919/integrated
Del: useless -- https://master.php.net/note/delete/73919/useless
Del: bad code -- https://master.php.net/note/delete/73919/bad+code
Del: spam -- https://master.php.net/note/delete/73919/spam
Del: non-english -- https://master.php.net/note/delete/73919/non-english
Del: in docs -- https://master.php.net/note/delete/73919/in+docs
Del: other reasons-- https://master.php.net/note/delete/73919
Reject -- https://master.php.net/note/reject/73919
Search -- https://master.php.net/manage/user-notes.php