Summing Values of an Array Grouping by Key

Asked

Viewed 164 times

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 ?

  • 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.

  • checks if my answer helps you

  • 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

  • And my answers helped?

  • I’ll try them out in a little while, but from the looks of things they’ll help.

  • 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

Show 2 more comments

1 answer

1


one of the solutions I found that always follows this pattern would be this

    function agrupamento($array_post)
    {
        $array_new = [];
        foreach ($array_post as $k => $v) {
            //retirar o numero e o caracter final do post
            $novachave = substr($k, 0, -2);
            //verifico se ela ja foi setada caso foi verifica se e um numero
            if (isset($array_new[$novachave]) and is_numeric($v)) {
                $array_new[$novachave] =  $array_new[$novachave] + $v;
                
                //verifica se e um numero 
            }elseif(is_numeric($v)){
                $array_new[$novachave]=$v;
            }
        }
        return $array_new;
    }
agrupamento($_POST);

Answer:

[ 
   [af_bm1] => 3,
   [af_om1] => 7 ,
   [af_a] => 11
]

example 2

function agrupamentocomfiltro($array_post)
{
    $array_new = [];
    $chavepermitidas = ['af_a', 'af_bm1', 'af_om1'];
    foreach ($array_post as $k => $v) {
        //controlador da chave
        $controlador = 0;

        //retirar o numero final do post
        $novachave = substr($k, 0, -2);

        //varre todas as chaves que você permitiu se contada
        foreach ($chavepermitidas as $value_permitido) {
            //verifica se a chave atual do POST esta na lista de chaves permitida
            if ($novachave == $value_permitido) {
                //caso esteja seta o controlador para 1 e sai do loop
                $controlador = 1;
                break;
            }
        }
        // verifica se o controlador e 1
        if ($controlador == 1) {

            //verifico se ela ja foi setada caso foi verifica se e um numero
            if (isset($array_new[$novachave]) and is_numeric($v)) {
                $array_new[$novachave] = $array_new[$novachave] + $v;

                //verifica se e um numero
            } elseif (is_numeric($v)) {
                $array_new[$novachave] = $v;
            }
        }
    }
    return $array_new;
}
  • They worked super well, all two versions, I just had to change the [] and ['af_a', 'af_bm1', 'af_om1'] for array() and array('af_a', 'af_bm1', 'af_om1']). I believe that due to PHP version of the server that works.

Browser other questions tagged

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