1
I have an array with items, and each with a sub-array where we have the values to be added, I’m trying to make each sub-array have its sum returned, and display the following result..
//Esse seria a forma correta do retorno da soma
{
"item-a": 50.5,
"item-b": 70.5
}
Yet you are returning me as follows..
/*
O primeiro 'item-a' até trás o resultado exato, já o segundo 'item-b'
soma o valor anterior com o valor que deveria ser aplicado ali. (50.5 + 70.5 = 121)
*/
{
"item-a": 50.5,
"item-b": 121
}
This is the code I’m looking for the solution to..
$items = array(
'item-a' => [
//valores a ser somado
'1' => 25.5,
'2' => 25.0
],
'item-b' => [
//valores a ser somado
'1' => 30.5,
'2' => 40.0
]
);
$valor = array();
//array items
foreach($items as $key => $res)
{
//sub-array com valores do item
foreach($res as $k => $val)
{
//somar
$somar += $val;
//retornar valor somado a cada item
$valor[$key] = $somar;
}
}
//imprimir array
return json_encode($valor, JSON_PRETTY_PRINT);
Thanks!