Two-dimensional array

0

I need to take the average of the grades presented in this exercise, the exercise told me to get grades by average and by subject but I really do not know how to make that average in php I have only managed to display the values

<?php
$calificacion = array(
    'Calificaciones : '=> array(
        "Por Promedio", 
        'nota parcial 1'=>4.1,
        'nota parcial 2'=>5.0), 
    'Por Materia: '=>array(
        "Algoritmia 1"=>3.9, 
        "Matematica 3"=>4.8));

foreach ($calificacion as $personas=>$info ) {
    echo $personas.'<br>';
    foreach ($info as $content) {
        echo $content.'<br>';
    }
}
?>
    
asked by DANIEL FELIPE LOPEZ VARGAS 15.08.2017 в 00:17
source

1 answer

0
//Primero que nada tu arreglo deberia quedar de esta manera
  $calificacion = array(
    'Calificaciones : '=> array(
        "Por Promedio" => array( 
             'nota parcial 1'=>4.1,
             'nota parcial 2'=>5.0)), 
        "Por Materia: "=> array(
              "Algoritmia 1"=>3.9, 
              "Matematica 3"=>4.8))
    ));

  o de lo contrario
  $calificacion = array(
        "Por Promedio" => array( 
             'nota parcial 1'=>4.1,
             'nota parcial 2'=>5.0), 
        "Por Materia: "=> array(
              "Algoritmia 1"=>3.9, 
              "Matematica 3"=>4.8)
    );

in this way you would be dividing in the arrangement the criteria by which you are going to compare By Average or By Subject without getting so entangled

Now to calculate the average you can make a function since you are going to repeat the same operation more than 1 time, 1 for the average notes and another for the notes per subject. It would stay like this

function average($arreglo){
   //va almacenando la sumatoria de los valores del arreglo
   $total = 0;
   //Recorro el arreglo para ir sumando sus valores
   foreach($arreglo as $elemento){
      $total += $elemento;
   }
   //Retorno el total entre la cantidad de elementos que comprenden el arreglo pasado por parámetro
   return $total/count($arreglo);
}

   //Ahora para usarlo sería:
   echo average($calificacion["Por Promedio"]); //En caso de haber declarado la variable calificacion como la ultima opcion que te mostre al comienzo

I hope it serves you, if you chose to put the first option of the one I gave you at the beginning to get to the arrangement where you have the values of the average serious notes

  echo average($calificacion['Calificaciones : ']['Por Promedio']);

It's all about how much you nest the arrangement. I hope it has served you

    
answered by 15.08.2017 в 23:05