note 39265 added to function.sort

From: Date: Thu, 22 Jan 2004 13:26:01 +0000
Subject: note 39265 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-64019@lists.php.net to get a copy of this message
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 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39265 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39265&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39265&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#64019) next »