获取php数组中特定条目的总和

时间:2015-05-13 12:46:36

标签: php json

我编写了一个PHP脚本,从api输出以下内容:

    array(197) {
  [0]=>
  array(2) {
    ["buyer_email"]=>
    string(25) "*****@live.co.uk"
    ["total"]=>
    array(2) {
      [0]=>
      string(4) "0.10"
      [1]=>
      string(4) "6.41"
    }
  }
  [1]=>
  array(2) {
    ["buyer_email"]=>
    string(19) "*****@hotmail.com"
    ["total"]=>
    array(8) {
      [0]=>
      string(4) "7.00"
      [1]=>
      string(4) "7.50"
      [2]=>
      string(5) "10.14"
      [3]=>
      string(5) "17.69"
      [4]=>
      string(5) "10.14"
      [5]=>
      string(5) "10.14"
      [6]=>
      string(5) "10.14"
      [7]=>
      string(5) "10.14"
    }
  }

这基本上显示了每个用户完成的购买。我想得到所有用户购买的总和。例如 "buyer_email": ****@live.co.uk, "total" : 6.51

我尝试过Luca建议的解决方案:

$json = '{"buyer_email":"****@live.co.uk","total":["0.10","6.41"]}';
$obj = json_decode($json);
$total = $obj->{'total'};

$sumTotal = 0;
for($i = 0; $i < count($total); $i++){
$sumTotal += $total[$i];
}

print $sumTotal;

它适用于单个条目,但不适用于多个条目?

1 个答案:

答案 0 :(得分:1)

那项工作:

$json = '{"buyer_email":"****@live.co.uk","total":["0.10","6.41"]}';
$obj = json_decode($json);
$total = $obj->{'total'};

$sumTotal = 0;
for($i = 0; $i < count($total); $i++){
$sumTotal += $total[$i];
}

print $sumTotal;