Doubt ascending / descending order

2

I have a form with which I collect the data in an array.

$dato1 = $_REQUEST['nombre'];
$dato2 = $_REQUEST['director'];
$dato3 = $_REQUEST['año'];
$dato4 = $_REQUEST['genero'];
$dato5 = $_REQUEST['duracion'];

$alumno = array("nombre" => "$dato1","director" => "$dato2","año" => "$dato3","genero" => "$dato4","duracion" => "$dato5");
$_SESSION['lista'][] = $alumno;

And then I have another form to indicate how I want to order, and a function for each field.

The function that orders me alphabetically, but I want to add ascending or descending order.

function comparatitulo ($x, $y) {
    if ($x['nombre'] == $y['nombre']){
        return 0;
    }elseif ($x['nombre'] < $y['nombre']){
        return -1;
    }else{
        return 1;
    }
}
uasort ($_SESSION['lista'], 'comparatitulo');
break;

Can someone help me?

Thanks in advance.

    
asked by Carlos Moran 15.11.2018 в 12:14
source

1 answer

1

When you compare the values in your function to order in ascending you use < and in desc >, so a very simple way with your code is to create a function to sort in ascending and another in descending and to use the one you need at every moment.

$a_tittles[0]['nombre'] = "aaa";
$a_tittles[1]['nombre'] = "bbb";
$a_tittles[2]['nombre'] = "ccc";

function comparatituloasc ($x, $y) {
   if ($x['nombre'] == $y['nombre']) { return 0;
   } else if ($x['nombre'] < $y['nombre']) { return -1;
   } else { return 1; }      
}

function comparatitulodesc ($x, $y) {
   if ($x['nombre'] == $y['nombre']) { return 0;
   } else if ($x['nombre'] > $y['nombre']){ return -1;
   } else { return 1; }      
}    

uasort ($a_tittles, 'comparatituloasc');    //Orden asc
foreach ($a_tittles as $title) { echo $title['nombre']."-"; }
//aaa-bbb-ccc-
uasort ($a_tittles, 'comparatitulodesc');    //Orden desc    
foreach ($a_tittles as $title) { echo $title['nombre']."-"; }
//ccc-bbb-aaa-
    
answered by 15.11.2018 / 12:45
source