0
I posted a question here this week, but it was negative for lack of more information, from then on I ended up solving the problem in question, so I will leave here the solution I found and if you want to implement feel free.
(1) What was the problem? I had a form (see below) of questions, where the user inserts numbers, I need to add these numbers according to the names of the fields, grouping them, then I have 2 af_bm1, 2 af_a and 2 af_om1.
<form method="post" action="" enctype="multipart/form-date">
<input class="af af_1" type="text" name="af_bm1_2"> <span>Pergunta 1</span>
<input class="af af_2" type="text" name="af_om1_1"> <span>Pergunta 2</span>
<input class="af af_3" type="text" name="af_a_1"> <span>Pergunta 3</span>
<input class="af af_4" type="text" name="af_a_2"> <span>Pergunta 4</span>
<input class="af af_5" type="text" name="af_om1_2"> <span>Pergunta 5</span>
<input class="af af_6" type="text" name="af_bm1_1"> <span>Pergunta 6</span>
</form>
Since I could not reach a code with the form in this format, I changed the field names to generate a different array and already group the fields with similar names, the fields then stayed like this:
<form method="post" action="" enctype="multipart/form-date">
<input class="af af_1" type="text" name="af_bm1[1]"> <span>Pergunta 1</span>
<input class="af af_2" type="text" name="af_om1[1]"> <span>Pergunta 2</span>
<input class="af af_3" type="text" name="af_a[1]"> <span>Pergunta 3</span>
<input class="af af_4" type="text" name="af_a[2]"> <span>Pergunta 4</span>
<input class="af af_5" type="text" name="af_om1[2]"> <span>Pergunta 5</span>
<input class="af af_6" type="text" name="af_bm1[1]"> <span>Pergunta 6</span>
</form>
That way I could use a foreach()
together with a array_sum()
, being like this:
$vars = $_POST; //Não faça isso em casa!!!
$res_totais = array();
foreach ($vars as $key => $value){
$res_totais[$key] = array_sum($value);
}
echo '<pre>'; print_r($res_totais); echo '</pre>';
Grudge:
Array(
[af_a] => 15
[af_bm1] => 24
[af_om1] => 30
)
I got the expected result, but my doubt continued, and if I could not change the names of the fields, how would I get this result?
a question, it will always follow this number pattern ?
– clone por
Yes, the similar ones will have sequential numbering af_a_1, af_a_2, af_a_3, on the screen they were scrambled, to avoid recognition of the pattern they are arranged.
– Gnomo Escalate
checks if my answer helps you
– clone por
I added another example with a filter of which key you want to be counted so you can make filters and only count the ones that interest you at the moment
– clone por
And my answers helped?
– clone por
I’ll try them out in a little while, but from the looks of things they’ll help.
– Gnomo Escalate
Blz, in case I’m sure to mark it as correct, in case something goes wrong, let me know that I can try to help
– clone por