How to generate sequential variables (e.g.: D1, D2, D3) and then merge everything into a single PHP variable

Asked

Viewed 32 times

-1

I have script using foreach that generates the variables $d, $m, that receive the value of a mysql query and puts this value in the input

echo "
<input type='text' name='tipo' value='".$d."'>
<input type='text' name='metragem' value='".$m."'>
";

Then I wanted each field to be unique, because the query returns several lines, so I added $n

$n = 0;
foreach($unidades as $unidade){
    $n++
    echo "
        <input type='text' name='tipo".$n."' value='".$d."'>
        <input type='text' name='metragem' value='".$m."'>
    ";
}

so far so good, but now I need to join all in a single variaval $dtotal and $mtotal, ex:

$mtotal = 'tipo'.$n1.'|'.'tipo'.$n.'|'.'tipo'.$n(quantos n tiverem);
  • "wanted every field to be unique", but what is the reason for this, identify in the javascript? If it is, it would be better to define the id and not the unique name. Using the same name (tipo[]) you can take an array of values and easily join by making a foreach, there are several examples here at Sopt.

  • 1

    Leandro, can reply to us if you need to "join" the fields at the time you are assembling the page, to display the total, or when you post the page, read all fields and join to add the value?

1 answer

1


You can solve your problem by creating the $mtotal and $dtotal within your own foreach, so:

$n = 0;
$mtotal = ''; // inicializa a variável mtotal
foreach($unidades as $unidade){
    $n++
    echo "
        <input type='text' name='tipo".$n."' value='".$d."'>
        <input type='text' name='metragem' value='".$m."'>
    ";

    //concatena a variável existente com o formato desejado
    $mtotal .= 'tipo'.$n.'|';

}

Doing it the same way $dtotal, that you didn’t give the example of how it would look.

  • David, perfect your idea if it is to show the total that already exists in the bank, but what if it is to join in the hour after a post? I made a comment in that sense, but reading your question I was doubtful, it would be nice to @leandro-marzullo answer this

  • I understand your doubt, is a valid question to be seen with Leandro Marzullo

  • 1

    I left a comment on the question.. by the example he gave $mtotal = 'tipo'.$n1.'|'.'tipo'.$n.'|'.'tipo'.$n(quantos n tiverem); it seems to me that you want to join right when it comes to putting together the page, the way it is in your answer

  • 1

    that’s right @Davidalves, valeeew!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.