note 39265 deleted from function.sort by didou
| From: | didou@php.net | Date: | Thu, 22 Jan 2004 13:39:07 +0000 |
| Subject: | note 39265 deleted from function.sort by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-64020@lists.php.net to get a copy of this message | ||
Note Submitter: sebastian01@hotmail.com
----
This function bubble sorts a 2.-dimensional (or table) array by a column.
Example:
$arr[0][col1] = "3";
$arr[0][col2] = "b";
$arr[0][col3] = "perro";
$arr[1][col1] = "1";
$arr[1][col2] = "c";
$arr[1][col3] = "vaca";
$arr[2][col1] = "2";
$arr[2][col1] = "a";
$arr[2][col2] = "gato";
$arr = SortByColumn ($arr, "col2", "ASC");
The result will be:
$arr[0][col1] = "2";
$arr[0][col2] = "a";
$arr[0][col3] = "gato";
$arr[1][col1] = "3";
$arr[1][col2] = "b";
$arr[1][col3] = "perro";
$arr[2][col1] = "a";
$arr[2][col1] = "c";
$arr[2][col2] = "vaca";
//----------------------------------------
// Función SortByColumn
//----------------------------------------
// Descripción: Ordena un matriz de 2 dimensiones (tabla) por una columna
// Parámetros:
// * matrix: Matriz
// * col: Nombre o índice de la columna a ordenar
// * order_direction: Dirección de ordenamiento, ascendente o descendente ['ASC',
'DESC']
//----------------------------------------
Function SortByColumn ($matrix, $col, $order_direction)
{
$order_direction = StrToUpper ($order_direction);
$n = SizeOf ($matrix);
For ($i = 0; $i < $n - 1; $i++)
{
For ($j = $i + 1; $j < $n; $j++)
{
If (($order_direction == "ASC" And $matrix[$i][$col] > $matrix[$j][$col]) Or
($order_direction == "DESC" And $matrix[$i][$col] < $matrix[$j][$col]))
{
$bubble = $matrix[$i];
$matrix[$i] = $matrix[$j];
$matrix[$j] = $bubble;
}
}
}
Return $matrix;
}
//----------------------------------------
Sebastián Trujillo