Dynamic table with PHP [closed]

-3

I'm creating a PivotTable using PHP.

The problem and the following I created a field to modify the values of the variable $conteudo of the body of the table but I can not change more than one field of the table someone can help me to solve this problem?

PS. to pass the field to be modified and as follows (field1, field2, field3)

<?php

/*
 * CABEÇALHO DA TABELA
 */
$campos = explode(',','id,nome,idade,sexo');
$conteudo = explode(',','1,funano,21,1');


/*
 * MODIFICADOR DE CAMPOS
 */
$modificador = explode(',','21');



echo '<table border="1px" width="100%">';
echo '<tr>';

foreach($campos as $x){
            echo '<th>'.$x.'</th>';
}
echo '</tr>';



/**
 * CONTEUDO DA TABELA
 */
echo '<tr>';
foreach($conteudo as $b){
    /*
     * COMPARANDO O MODIFICADOR COM O CAMPO DA TABELA
     */
    foreach($modificador as $m) {


        if ($b == $m) {
            echo '<th>' . 'campo' . '</th>';
        } else {
            echo '<td>'.$b.'</td>';
        }
    }
}
echo '</tr>';
echo '</table>';

The problem happens when I try to add another field to modify, for example:

$modificador = explode(',','21,funano');

    
asked by anonymous 27.10.2014 / 13:19

1 answer

3

The problem is that you are printing the field value or the modifier every time you check all $m and ends up printing more than once per field .

You can check when match of $m with $b if it has already been printed:

foreach($conteudo as $b){
    /*
     * COMPARANDO O MODIFICADOR COM O CAMPO DA TABELA
     */
    $isEqual = false;
    foreach($modificador as $m) {

        if ($b == $m) {
            echo '<th>' . 'campo' . '</th>';
            $isEqual = true; // se forem iguais imprime campo
        }
    }
    if(!$isEqual) echo '<td>'.$b.'</td>';//senão imprime o valor de $b
}

phpfiddle

Or you can use PHP's in_array function that compares if an element is in the array :

foreach($conteudo as $b){
    /*
     * COMPARANDO O MODIFICADOR COM O CAMPO DA TABELA
     */
    if (in_array($b, $modificador))
        echo '<th>' . 'campo' . '</th>';
    else
        echo '<td>'.$b.'</td>';
}
    
27.10.2014 / 14:34