Create table vertically with PHP

2

I'm starting with PHP and I have to do an exercise to show calculated results from an array in a table. I get the data but at the time of creating the table I do not give the formula to do it horizontally. I mean, I get to do it like this:

But I need to do it like this:

That is, vertically. After many laps I do not give with the solution. I put the code that I used:

             Frequencies                           

        #verde{

            background: green;
            color: white;
            text-align: center;
        }

        table{
          border-collapse:collapse;
          background-color: #97BB00;
          border-color: white;
          text-align: center;

        }

    </style>
</head>
<body>
    <table  border="solid" align="center" >
        <?php
        //Vavriables
        $valores = array(7, 19, 25, 12, 23, 15, 8, 16);

        $total = array_sum($valores);


        echo "<tr><td id=\"verde\"><b>X1</b></td>";
        for ($i = 0; $i < count($valores); $i++) {
            $indice = $i + 1;
            echo "<td> <b>$indice</b> </td>";
        }
        echo "<td id=\"verde\"><b>TOTAL<b></td>";
        echo "</tr>";

        echo "<tr><td id=\"verde\"><b>Frecuencia<br> absoluta</b></td>";
        foreach ($valores as $value) {
            echo "<td>$value</td>";
        }
        echo "<td id=\"verde\"><b>$total</b></td>";
        echo "</tr>";

        echo "<tr><td id=\"verde\"><b>Frecuencia<br> absoluta <br>acumulada</b></td>";
        $frecuenciaAbAcumulada = 0;
        foreach ($valores as $value) {
            $frecuenciaAbAcumulada += $value;
            echo "<td>$frecuenciaAbAcumulada</td>";
        }
        echo "<td id=\"verde\"><b>$total</b></td>";
        echo "</tr>";

        echo "<tr><td id=\"verde\"><b>Frecuencia<br>relativa</b></td>";
        $fr = 0;
        $frecuenciaRelativa = 0;
        foreach ($valores as $value) {
            $fr = $value / array_sum($valores);
            $frecuenciaRelativa = round($fr, 2, PHP_ROUND_HALF_UP);
            echo "<td>$frecuenciaRelativa</td>";
        }

        $totalFrecuenciaRelativa = 0;
        foreach ($valores as $value) {
            $totalFrecuenciaRelativa += ($value / array_sum($valores));
        }
        echo "<td id=\"verde\"><b>$totalFrecuenciaRelativa</b></td>";
        echo "</tr>";

        echo "<tr><td id=\"verde\"><b>Frecuencia<br>Relativa<br>acumulada</b></td>";
        $fra = 0;
        $frecuenciaRelativaAcumulada = 0;

        foreach ($valores as $value) {
            $frecuenciaRelativaAcumulada += $value / array_sum($valores);
            $fra = round($frecuenciaRelativaAcumulada, 2, PHP_ROUND_HALF_UP);
            echo "<td>$fra</td>";
        }

        echo "<td id=\"verde\"><b>$fra</b></td>";
        echo "</tr>";
        ?>

    </table>

</body>

Greetings.

    
asked by Carlos Rayón Álvarez 22.10.2017 в 18:46
source

3 answers

1

I propose the following solution.

  • The code is written in an orderly and clean way, without so many echoes everywhere. Help for those purposes to create a variable to which we are concatenating everything.
  • Consider the use of number_format to get two-digit decimals after the period.
  • I did not understand well what you want to present in the last row ( Total ), I assumed that there you would want a vertical sum of all the values of each cell. If not, it will not be problematic to change that value.
  • I have not applied styles directly to the table, it is not recommended. It is recommended to use class names and apply styles using CSS. That way your HTML document is more independent and if you want to change any style element you modify the CSS without having to go through all the HTML. You can change the values to your liking in terms of colors and other things ...

Code

VIEW DEMO

<?php 

    /*Declaramos todas nuestras variables fuera del bucle*/
    $valores = array(7, 19, 25, 12, 23, 15, 8, 16);
    $sum_valores=array_sum($valores);

    $frecuenciaAbAcumulada = 0;
    $sum_faa=0;

    $frecuenciaRelativa = 0;
    $sum_fr=0;
    $fr = 0;

    $frecuenciaRelativaAcumulada = 0;
    $sum_fra=0;

    /*Usaremos una variable para ir construyendo la tabla*/

    $tablaHTML="<table>";
    $tablaHTML.="<th>X</th>
                 <th>Frecuencia absoluta</th>
                 <th>Frecuencia absoluta acumulada</th>
                 <th>Frecuencia relativa</th>
                 <th>Frecuencia relativa acumulada</th>";

    /*Leemos las claves y valores del array. Usamos $k+1 para los números*/
    foreach ($valores as $k=>$v) 

    {
        /*Calculamos valores*/
        $contador=$k+1;
        $frecuenciaAbAcumulada += $v;
        $sum_faa+=$frecuenciaAbAcumulada;

        $fr = $v / $sum_valores;
        $frecuenciaRelativa = number_format(round($fr, 2, PHP_ROUND_HALF_UP),2);
        $sum_fr+=$fr;

        $frecuenciaRelativaAcumulada += $v / $sum_valores;
        $fra = number_format(round($frecuenciaRelativaAcumulada, 2, PHP_ROUND_HALF_UP),2);
        $sum_fra+=$fra;

        /*Agregamos valores a la tabla*/
        $tablaHTML.="<tr>";
        $tablaHTML.="<td>$contador</td>"; 
        $tablaHTML.="<td>$v</td>"; 
        $tablaHTML.="<td>$frecuenciaAbAcumulada</td>"; 
        $tablaHTML.="<td>$frecuenciaRelativa</td>"; 
        $tablaHTML.="<td>$fra</td>";
        $tablaHTML.="</tr>";

   }

    /*La línea de Totales la agregamos fuera del bucle*/
    $tablaHTML.="<tr class=\"total\">";
    $tablaHTML.="<td>Total</td>";
    $tablaHTML.="<td>$sum_valores</td>";
    $tablaHTML.="<td>$sum_faa</td>";
    $tablaHTML.="<td>$sum_fr</td>";
    $tablaHTML.="<td>$sum_fra</td>";
    $tablaHTML.="</tr>";

    $tablaHTML.="</table>";

    /*Imprimimos la tabla*/
    echo $tablaHTML;

?>

Result

table {
  border-collapse: collapse;
  text-align: center;
}

table,
th,
td {
  border: 1px solid black;
}

th {
  background-color: #089541;
}

tr:hover {
  background-color: #f5f5f5
}

tr:nth-child(even) {
  background-color: #a0bf8d
}

.total td {
  background-color: #5fff00;
  font-weight: bold;
}
<table>
  <th>X</th>
  <th>Frecuencia absoluta</th>
  <th>Frecuencia absoluta acumulada</th>
  <th>Frecuencia relativa</th>
  <th>Frecuencia relativa acumulada</th>
  <tr>
    <td>1</td>
    <td>7</td>
    <td>7</td>
    <td>0.06</td>
    <td>0.06</td>
  </tr>
  <tr>
    <td>2</td>
    <td>19</td>
    <td>26</td>
    <td>0.15</td>
    <td>0.21</td>
  </tr>
  <tr>
    <td>3</td>
    <td>25</td>
    <td>51</td>
    <td>0.20</td>
    <td>0.41</td>
  </tr>
  <tr>
    <td>4</td>
    <td>12</td>
    <td>63</td>
    <td>0.10</td>
    <td>0.50</td>
  </tr>
  <tr>
    <td>5</td>
    <td>23</td>
    <td>86</td>
    <td>0.18</td>
    <td>0.69</td>
  </tr>
  <tr>
    <td>6</td>
    <td>15</td>
    <td>101</td>
    <td>0.12</td>
    <td>0.81</td>
  </tr>
  <tr>
    <td>7</td>
    <td>8</td>
    <td>109</td>
    <td>0.06</td>
    <td>0.87</td>
  </tr>
  <tr>
    <td>8</td>
    <td>16</td>
    <td>125</td>
    <td>0.13</td>
    <td>1.00</td>
  </tr>
  <tr class="total">
    <td>Total</td>
    <td>125</td>
    <td>568</td>
    <td>1</td>
    <td>4.55</td>
  </tr>
</table>
    
answered by 22.10.2017 / 20:59
source
0

Still missing, but it's something like that (the first 3 columns):

<?php
$valores = array(7, 19, 25, 12, 23, 15, 8, 16);
$total = array_sum($valores);
?>
<table>
    <tr>
        <td>x</td>
        <td>Frecuencia absoluta</td>
        <td>Frecue...acumulada</td>
        <td>freq relativa</td>
        <td>freq relat acumuladda</td>
    </tr>
    <?php
    $indice = 0;
    $acumulado = 0;
    foreach ($valores as $value) {
        $indice++;
        $acumulado += $value;
        echo "<tr>";
        echo "<td>" . $indice . "</td>";
        echo "<td>" . $acumulado . "</td>";
        $fr = 0;
        $frecuenciaRelativa = 0;
            $fr = $value / array_sum($valores);
            $frecuenciaRelativa = round($fr, 2, PHP_ROUND_HALF_UP);
            echo "<td>$frecuenciaRelativa</td>";
    }
    ?>
</table>
    
answered by 22.10.2017 в 19:18
0

When you have problems of this type I recommend that you first make the table only with HTML, then add styles and once you have it clear you can see how to build it with PHP.

The HTML you are looking for would be this one (simplified version):

.green {
	border-collapse:collapse;
	background-color: #97BB00;
}
	.green td,
	.green th,
	.green tr {
		border: 1px solid white;
		text-align: center;
	}
	.green td,
	.green th {
		padding: .2em .8em;
	}
#verde{
	background: green;
	color: white;
}
<table class="green" align="center">

	<tr>
		<td id="verde"><b>X1</b></td>
		<td id="verde"><b>Frecuencia<br> absoluta</b></td>
		<td id="verde"><b>Frecuencia<br> absoluta <br>acumulada</b></td>
	</tr>
	<tr>
		<td><b>1</b></td>
		<td>7</td>
		<td>7</td>
	</tr>
	<tr>
		<td><b>2</b></td>
		<td>19</td>
		<td>26</td>
	</tr>
	<tr>
		<td id="verde"><b>TOTAL</b></td>
		<td id="verde"><b>125</b></td>
		<td id="verde"><b>125</b></td>
	</tr>
</table>

There are good tutorials on construction of tables in: link and link

And a possible solution:

<?php

/**
 * Declaración funciones
 *
 */
    function echoVerde( $str ) {

        echo '<td id="verde"><b>' . $str . '</b></td>';
    }
    function echoValue( $value, $strong=FALSE ) {

        if ( $strong )
            echo '<td><b>' . $value . '</b></td>';

        else
            echo '<td>' . $value . '</td>';
    }

    function calculaAcumuladas( $valores ) {

        $arr = array();
        $temp = 0;
        foreach ( $valores as $value ) {

            $temp += $value;
            $arr[] = $temp;
        }


        return $arr;
    }
    function calculaFAAs( $valores_fa ) {

        return calculaAcumuladas( $valores_fa );
    }
    function calculaFRs( $valores_fa ) {

        $arr = array();
        $total = array_sum( $valores_fa );

        foreach ( $valores_fa as $key => $fa ) {

            $temp = $fa / $total;
            $arr[] = number_format( round( $temp, 2, PHP_ROUND_HALF_UP ), 2 );
        }

        return $arr;
    }
    function calculaFRAs( $valores_fr ) {

        return calculaAcumuladas( $valores_fr );
    }


/**
 * Declaración variables
 * 
 */

    $valores_fa  = array( 7, 19, 25, 12, 23, 15, 8, 16 );

    $valores_faa = calculaFAAs( $valores_fa );
    $valores_fr  = calculaFRs( $valores_fa );
    $valores_fra = calculaFRAs( $valores_fr );

    $total_fa    = array_sum( $valores_fa );
    $total_faa   = array_sum( $valores_faa );
    $total_fr    = array_sum( $valores_fr );
    $total_fra   = array_sum( $valores_fra );

    /*echo '<pre>';
    var_dump( $valores_fr );
    echo '</pre>';
    die(); /**/
?>

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8">
        <title>Tabla</title>

        <style type="text/css">

            #verde{
                background: green;
                color: white;
                text-align: center;
            }

            table{
              border-collapse:collapse;
              background-color: #97BB00;
              border-color: white;
              text-align: center;
            }

        </style>
    </head>
    <body>
        <table  border="solid" align="center" >
            <thead>
                <tr>
<?php
    echoVerde( 'X1' );
    echoVerde( 'Frecuencia<br> absoluta' );
    echoVerde( 'Frecuencia<br> absoluta <br>acumulada' );
    echoVerde( 'Frecuencia<br>relativa' );
    echoVerde( 'Frecuencia<br>Relativa<br>acumulada' );

    //Fin primera fila
?>
            </tr>
        </thead>
        <tbody>
            <tr>
<?php 

    //Mostrando datos

    //Imprime filas con los tados
    $indice = 1;
    foreach ( $valores_fa as $key => $fa ) {

        echoValue( $indice, TRUE );
        echoValue( $fa );
        echoValue( $valores_faa[ $key ]);
        echoValue( $valores_fr[ $key ]);
        echoValue( $valores_fra[ $key ]);

        echo '</tr>';
        echo '<tr>';

        $indice++;
    }

    //Imprime fila con los totales
    echoVerde( 'TOTAL' );
    echoVerde( $total_fa );
    echoVerde( $total_faa );
    echoVerde( $total_fr );
    echoVerde( $total_fra );

?>
                </tr>
            </tbody>
        </table>
    </body>
</html>
    
answered by 22.10.2017 в 19:19