Hi,

Say I were to get an array from a database:

$sql = mysql_query("SELECT * FROM table");
while($r = mysql_fetch_array($sql)) {
$arr[] = ('Name => $r["Name"]', 'Lname => $r["LName"]');

}

Ignore bad syntax in the above, I know....

Anyway, how would I be able to sort the array by Lname for example? I know I could just do ORBER BY LName however in my real situation i need to sort an array .

Thanks

    //BUBBLE SORT

    $switched = false;

    / you don't have to compare the last variable in the array one before it becuase they are in order
    /
    //$length = length of array
    for($i = $length-1; $i>=0; $i--)
    {
    for($j = 0; $j < $i; $j++)
    {
    /hmmm, this is c coding now, so
    try to transfer it over to php with your own variables, your own array
    /

    if(array[j] > array[j+1])
    {
    temp = array[j];
    array[j] = array[j+1];
    array[j+1] = temp;
    $switched = true;
    }
    }
    if(!$switched)
    return 0;
    }

    /
    I don't know how your array is setup, but you shouldn't have trouble converting this to your needs
    i don't know if comparison between strings in this way is possible, but go for it, if not, you will have to take the first character from the string, turn it into ascii int, then compare it
    /

      function sortBy(&$arr,$by)
      { $arrSize = sizeof($arr);
      if ($arrSize>0)
      { $index = array();
      for ($i=0;$i<$arrSize;$i++) // rebuild array for sorting by $by ..
      $index[$arr[$i][$by]] = $arr[$i];
      ksort($index); // .. sort ..
      $i=0;
      foreach ($index as $entry) // .. and copy back to $arr
      { $$arr[$i] = $entry;
      $i++;
      }
      }
      }

      This method requires a lot of memory and cpu time
      but should do the job for small to medium sized arrays.

      Hope this to be helpful,

      Daniel

        Write a Reply...