Tema: FAQ's de PHP
Ver Mensaje Individual
  #112 (permalink)  
Antiguo 11/09/2004, 18:02
HiperJP
 
Fecha de Ingreso: enero-2004
Ubicación: Santiago
Mensajes: 127
Antigüedad: 20 años, 2 meses
Puntos: 0
Creando un menú de lista por medio de una función.

Tema: Funciones en PHP

Pregunta:
¿Como puedo crear por medio de una función un menu de lista pasandole como parámetros el nombre, cadena de etiquetas y cadena de valores?.

Respuesta:

Puedes utilizar esta pequeña función creada por mi (lee las notas IMPORTANTES)

Código PHP:
/* ### Function to create listbox from values and labels in arrays (Nº labels = Nº values). ###
* Compatible with PHP4 (function array_combine() must be present).
* @param string $nombre: The SELECT name.
* @param string $arr_etiquetas (comma separated or \n): The labels of the SELECT.
* @param string $arr_valores (comma separated or \n): The values of the SELECT.
* ************************************************************************************
* Author: Jean Pierre Martínez @ 26-07-2004 13:45 [[email protected]]

* Por favor notificame antes o después de realizar cualquier cambio, te lo agradeceré. :P
*/
function combinedListbox ($nombre$str_etiquetas$str_valores) {
if (!isset(
$nombre)) {
trigger_error('combinedListbox() expects parameter 1 to be defined, NULL given'E_USER_WARNING); 
     return 
null;
}
if (!
is_string($str_etiquetas)) {
trigger_error('combinedListbox() expects parameter 2 to be string, '.gettype($str_etiquetas).' given'E_USER_WARNING); 
     return 
null;
}
if (!
is_string($str_valores)) {
trigger_error('combinedListbox() expects parameter 3 to be string, '.gettype($str_valores).' given'E_USER_WARNING); 
     return 
null;
}
 
// Creamos array con elementos de etiqueta/valor (debe ser la misma cantidad en ambos).
$arr_etiquetas split("[,\n]"$str_etiquetas);
$arr_valores split("[,\n]"$str_valores);
 
// Verificar que la cantidad de etiquetas sea igual al de valores.
if (count($arr_etiquetas) != count($arr_valores)) {
trigger_error('combinedListbox() must contain an equal number of keys and values'E_USER_WARNING); 
     return 
null;
}
 
// Crear array de elementos combinados.
$array_listbox array_combine($arr_etiquetas$arr_valores);
 
$listbox "<SELECT NAME=\"$nombre\">\n";
foreach (
$array_listbox as $etiqueta => $valor)
{
$etiqueta trim($etiqueta);
$valor trim($valor);
$listbox .= " <OPTION VALUE=\"$valor\">$etiqueta</OPTION>\n";
}
$listbox .= "</SELECT>\n";
return 
$listbox;

IMPORTANTE:
Esta función utiliza la función (valga la redundancia) del lenguaje array_combine() que viene incluida con PHP5, para los usuarios de PHP4 pueden utilizar ésta misma función del mismo nombre la cual, en caso de trasladar la funcion combinedListbox() a PHP5, no entrará en conflicto con la que trae ésta.

Código PHP:
// Función 'array_combine' para PHP4.
if (!function_exists('array_combine')) 

    function 
array_combine($keys$values
    { 
        if (!
is_array($keys)) { 
            
trigger_error('array_combine() expects parameter 1 to be array, ' gettype($keys) . ' given'E_USER_WARNING); 
            return 
null
        } 
        if (!
is_array($values)) { 
            
trigger_error('array_combine() expects parameter 2 to be array, ' gettype($values) . ' given'E_USER_WARNING); 
            return 
null
        } 
        if (
count($keys) !== count($values)) { 
            
trigger_error('array_combine() Both parameters should have equal number of elements'E_USER_WARNING); 
            return 
false
        } 
        if (
count($keys) === || count($values) === 0) { 
            
trigger_error('array_combine() Both parameters should have number of elements at least 0'E_USER_WARNING); 
            return 
false
        } 
        
$keys    array_values($keys); 
        
$values array_values($values); 
        
$combined = array (); 
        for (
$i 0$cnt count($values); $i $cnt$i++) { 
            
$combined[$keys[$i]] = $values[$i]; 
        } 
        return 
$combined
    } 


Última edición por HiperJP; 11/09/2004 a las 18:06