1

Tengo el siguiente código para mostrar una tabla en PHP

<?php

$harvest = Array ( 
       Array ( 
                     Array ( 
                                    'PRODUCT' => 'ROSE' ,
                                    'VARIETY' => 'ADELE', 
                                  'GOLD' => 160, 
                                    'NORMAL' => 0 ,
                                    'TOTAL' => 160 
                                  ) ,
                     Array ( 
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ALESSO' ,
                                    'GOLD' => 1320 ,
                                    'NORMAL' => 550, 
                                    'TOTAL' => 1870 
                                  ) ,
                     Array ( 
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ANASTACIA' ,
                                    'GOLD' => 440 ,
                                    'NORMAL' => 150 ,
                                    'TOTAL' => 590 
                                  ),
                     Array ( 
                                    'PRODUCT' => 'ROSE1',
                                  'VARIETY' => 'ANASTACIA1' ,
                                  'GOLD' => 420 ,
                                    'NORMAL' => 120 ,
                                    'TOTAL' => 540 
                                  ),
                     Array ( 
                                    'PRODUCT' => 'ROSE1',
                                    'VARIETY' => 'ANASTACIA1', 
                                    'GOLD' => 440 ,
                                    'NORMAL' => 100 ,
                                    'TOTAL' => 540 
                                  ),
                     Array ( 
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2',
                                    'GOLD' => 640, 
                                    'NORMAL' => 0, 
                                    'TOTAL' => 640 
                                  ),
                     Array ( 
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2' ,
                                    'GOLD' => 440, 
                                    'NORMAL' => 440, 
                                    'TOTAL' => 880 
                                   )
                    )


     );


$arrayThead = array();
      for ($i=0; $i < count($harvest) ; $i++) {
        array_push($arrayThead, array_keys($harvest[$i][0]));
      }

      $totalByProduct = array();
      foreach ($harvest as $items) {
          foreach ($items as $item) {
              if(!key_exists($item['PRODUCT'], $totalByProduct)){
                  $totalByProduct[$item['PRODUCT']] = $item;
                  unset($totalByProduct[$item['PRODUCT']]['VARIETY']);
                  continue;
              }
              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $totalByProduct[$item['PRODUCT']][$th] += $item[$th];
                  }
                }
              }
          }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayComplete = array();
      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] != 'PRODUCT' && $arrayThead[$i][$j] != 'VARIETY'){
            array_push($arrayComplete, $arrayThead[$i][$j]);
          }
        }
      }


      $arrayFinal = array();
      for ($j=0; $j < count($arrayComplete) ; $j++) {
        array_push($arrayFinal, $arrayfoot[$arrayComplete[$j]]);
      }

    //  exit;

      $body = '';
      $body .= '<table style="border: 1px solid black;border-collapse: collapse;width: 100%;font-family:Calibri;">';
      $body .= '<thead style="background-color:#f3f4f5;">';
      $body .= '<tr>';

      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
            $body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
          }else{
            $body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
          }
        }
      }
      $body .= '</tr>';
      $body .= '</thead>';
      $body .= '<tbody>';

      for ($k=0; $k < count($harvest); $k++) {
        for ($a=0; $a < count($harvest[$k]) ; $a++) {
          $body .= '<tr>';
          for ($i=0; $i < count($arrayThead) ; $i++) {
            for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
              if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
                $body .= '<td style="border: 1px solid black;font-size:12px;">'.$harvest[$k][$a][$arrayThead[$i][$j]].'</td>';
              }else{
                $body .= '<td style="border: 1px solid black; text-align:right;font-size:12px;">'.number_format($harvest[$k][$a][$arrayThead[$i][$j]]).'</td>';
              }
            }
          }
          $body .= '</tr>';
          foreach ($totalByProduct as $key => $value) {
            if($value["PRODUCT"] == $harvest[$k][$a]['PRODUCT']){
              $body .= '<tr>';
              $body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;">TOTAL '.$value["PRODUCT"].'</th>';
              $body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;"></th>';

              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $body .= '<th style="border: 1px solid black;text-align:right;font-size:12px;">'.number_format($value[$th]).'</th>';
                  }
                }
              }
              $body .= '</tr>';
            }
          }
        }
      }

      $body .= '</tbody>';
      $body .= '<tfoot>';
      $body .= '<tr>';
      $body .= '<th style="border: 1px solid black;text-align:left;">TOTAL GENERAL</th>';
      $body .= '<th style="border: 1px solid black;"></th>';

      for ($i=0; $i < count($arrayFinal) ; $i++) {
        $body .= '<th style="border: 1px solid black;text-align:right;">'.number_format($arrayFinal[$i]).'</th>';
      }

      $body .= '</tr>';
      $body .= '</tfoot>';
      $body .= '</table>';

      echo $body;

Necesito colocar una fila con el total de GOLD, NORMAL y TOTAL dentro de la tabla, pero de acuerdo al producto.

Si desea ver cómo funciona el código, puede copiar el código y pegarlo en esta página: PHPTESTER

Necesito mostrar a la mesa algo como esto:

-------------------------------------------------------------------
  PRODUCT     |   VARIETY   |  GOLD    |  NORMAL |  TOTAL         |  
-------------------------------------------------------------------
   ROSE       |   ADELE     |  160     |  0      |     160        |
-------------------------------------------------------------------
   ROSE       |   ALESSO    |  1320    |  550    |    1870        |
-------------------------------------------------------------------
   ROSE       |  ANASTACIA  |  440     |    150  |  590           |
-------------------------------------------------------------------
   TOTAL ROSE |             |  1920    |  700    |  2620          |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  420     |  120    |  540           |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  440     |    100  |  540           |
-------------------------------------------------------------------
 TOTAL ROSE1  |             |  860     |  220    |  1080          |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  640     |    0    |  640           |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  440     |    440  |  880           |
-------------------------------------------------------------------
  TOTAL ROSE2 |             |  1080    |  440    |  1520          |
-------------------------------------------------------------------
 TOTAL GENERAL|             |  3860    |  1360   |  5220          |
-------------------------------------------------------------------

Espero me puedan ayudar, gracias!

7
  • Y siempre se cumple que las columnas numéricas son GOLD, NORMAL y TOTAL? Porque, en ese caso, ponerlas explícitamente en vez de adentro de un foreach te simplificaría un poco las cosas. Segundo, no está claro qué no te resulta por ahora.
    – ffflabs
    el 31 mar. 2017 a las 20:50
  • No, pueden ser más a parte de GOLD, NORMAL, TOTAL siempre es igual el 31 mar. 2017 a las 21:05
  • Sería bueno agregar que, dejando de lado toda la complejidad de tu abstracción, lo único que te está faltando es la lógica para no imprimir los subtotales en cada fila
    – ffflabs
    el 31 mar. 2017 a las 21:24
  • Me sonaba una pregunta sobre esos datos: es.stackoverflow.com/questions/58960/…. Creo que podrías resolverlo desde tu consulta SQL... agrupando y obteniendo un resultado por cada fila con lo que quieras. Si existen las bases de datos es para algo. Saludos.
    – A. Cedano
    el 1 abr. 2017 a las 14:11
  • Gracias por tu consejo, pero estoy tratando de hacerlo y no he podido! @A.Cedano el 1 abr. 2017 a las 16:51

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.