How to join values in common php array?

2

I have the array

$vetor[0]['codigo'] = '1';
$vetor[0]['valor']  = '4';

$vetor[1]['codigo'] = '1';
$vetor[1]['valor']  = '2';

$vetor[2]['codigo'] = '2';
$vetor[2]['valor']  = '2';

I need to merge all values with equal codes. Doing the above example looks like this:

Code 1 has a value of 6

And code 2 gets value 2

Does anyone have any idea how to do this?

    
asked by anonymous 16.05.2018 / 18:04

3 answers

1

I would do so:

$arrayFinal = array();

for($x = 0; $x < count($vetor); $x++){

    $codigo = $vetor[$x]['codigo'];
    if(array_key_exists($codigo, $arrayFinal)){
        $arrayFinal[$codigo]['valor'] += $vetor[$x]['valor'];
        continue;
    }
    $arrayFinal[$codigo] = array("codigo" => $codigo, "valor" => $vetor[$x]['valor']);
}
print_r($arrayFinal);

In this way it will add only elements that have the same code.

    
16.05.2018 / 19:02
1

I did not have time to test, but if I follow the logic, it should work.

    $resultado = [];
        for(i =0; i<sizeof($vetor); i++){
            $resultado[$vetor[i]] = $resultado[$vetor[i]] + $vetor[i]['valor'];
        }

In this code the position of the result vector will be the id

    
16.05.2018 / 18:24
0

You can do this:

$codigo=$valor=0;
for ($i=0; $i < count($vetor); $i++) { 
    $codigo+=$vetor[$i]['codigo'];
    $valor+=$vetor[$i]['valor'];
}
unset($vetor);//para eliminar o array vetor anterior
$vetor['codigo']=$codigo;
$vetor['valor']=$valor;
print_r($vetor);
    
16.05.2018 / 18:14