Calculate values in sub array [PHP]

Asked

Viewed 385 times

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!

3 answers

1


This simple change solves your problem

$valor = array();
//array items
foreach($items as $key => $res)
{
    //sub-array com valores do item
    foreach($res as $k => $val)
    {
        //retornar valor somado a cada item
        isset($valor[$key]) ? $valor[$key] += $val : $valor[$key] = $val;
    }
}

This is because you haven’t reset the $sum variable (which is unnecessary btw) in the first loop iteration

1

PHP provides a native set of functions to work with arrays, are the Array Functions. Array Functions allow accessing and manipulating arrays and are supported both simple and multi-dimensional arrays.

For your question we will use two functions a array_sum ( array $array ) : number which returns the sum of the elements of an array and array_map ( callable $callback , array $array1 \[, array $... \] ) : array which applies a certain function to all elements of an array or array group, the quantity of which must be the same as the number of accepted parameters passed as callback to map_array.

The logic of this example is to use the function array_map to apply array_sum in the elements of $items($item-a and $item-b)

<?php

  $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
    ]
  );


// Aplica a função array_sum aos arrays que compõe $items
$resultado = array_map('array_sum', $items);


// Exibe o resultado
print_r( json_encode( $resultado, JSON_PRETTY_PRINT ));
?>

The result is:

{ "item-a": 50.5, "item-b": 70.5 }

0

The only problem I’m seeing is that you’re not starting the variable $somar.

This variable should receive the value 0 at the beginning of each loop, thus:

foreach($items as $key => $res)
{
    $somar = 0;
    //sub-array com valores do item
    foreach($res as $k => $val)
    {
        //somar
        $somar += $val;
        //retornar valor somado a cada item
        $valor[$key] = $somar;
    }
}

Browser other questions tagged

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