With making a Count within the array

Asked

Viewed 83 times

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 recover the total sum of the value field. How can I do this in php?

2 answers

5

If you’re using php version 5.5 combine the function array_column() to extract a key from a multidimensional array. With this call array_sum() adding together the elements:

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

For versions older than 5.5 it is possible to get the same result with array_map().

$valores = array_map(function($item){ return $item['valor'];}, $arr);
echo array_sum($valores);

2

You can use the 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
  • Wow, I did some crazy foreach the other day, with array_keys and a lot of nonsense. Sign that I need to give a studied in these array functions

Browser other questions tagged

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