With making a count inside the array

3

Well I have the following array:

array (size=3)
0 => 
array (size=5)
  'valor' => string '10.00' (length=5)
  'forma' => string '1' (length=1)
  'parcelas' => string '' (length=0)
  'verifica_nome' => string '' (length=0)
  'cliente' => string '' (length=0)
1 => 
array (size=5)
  'valor' => string '1.51' (length=4)
  'forma' => string '1' (length=1)
  'parcelas' => string '' (length=0)
  'verifica_nome' => string '' (length=0)
  'cliente' => string '' (length=0)
2 => 
array (size=5)
  'valor' => string '10.00' (length=5)
  'forma' => string '1' (length=1)
  'parcelas' => string '' (length=0)
  'verifica_nome' => string '' (length=0)
  'cliente' => string '' (length=0)

I need to retrieve the total sum of the value field. How can I do this in php?

    
asked by anonymous 15.03.2017 / 18:37

2 answers

5

If you are using version 5.5 of php, combine the array_column() function to extract a key from a multidimensional array. With this call array_sum() that adds the elements:

$arr = array(array('id' => 1, 'valor' => 350), array('id' => 2, 'valor' => 200));
echo array_sum(array_column($arr, 'valor')); //550

For versions prior to 5.5 you can get the same result with array_map() .

$valores = array_map(function($item){ return $item['valor'];}, $arr);
echo array_sum($valores);
    
15.03.2017 / 18:43
2

You can use array_reduce, it reduces an array to a single value

$array = [
    ['valor'=>10],
    ['valor'=>30],
    ['valor'=>40]
    ];

$arrayTotal =  array_reduce($array,function($carry,$item){
    $carry += $item['valor'];
    return $carry;
},0);

echo $arrayTotal; //80
    
15.03.2017 / 19:48