在多维PHP数组中求和

时间:2017-02-06 14:43:19

标签: php arrays multidimensional-array sum

我有一个数组,它返回如下。我需要添加它们的值,但取决于帐户“cuenta”,分支“ramo”,子分支“subramo”,特定“especifica”或子特定“subespecifica”。

array(5) {
  [0]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "2"
    ["especifica"]=>
    string(2) "19"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(6) "354.00"
  }
  [1]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "2"
    ["especifica"]=>
    string(2) "11"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(6) "543.74"
  }
  [2]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "2"
    ["especifica"]=>
    string(2) "11"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(6) "985.54"
  }
  [3]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "1"
    ["especifica"]=>
    string(1) "8"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(6) "177.00"
  }
  [4]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "1"
    ["especifica"]=>
    string(1) "2"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(5) "88.50"
  }
}

我需要根据我刚提到的内容返还总金额。也就是说:

array(4) {
  [0]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "2"
    ["especifica"]=>
    string(2) "19"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(6) "354.00"
  }
  [1]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "2"
    ["especifica"]=>
    string(2) "11"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(6) "1529.28"
  }
  [2]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "1"
    ["especifica"]=>
    string(1) "8"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(6) "177.00"
  }
  [3]=>
  array(6) {
    ["cuenta"]=>
    string(1) "1"
    ["ramo"]=>
    string(1) "1"
    ["subramo"]=>
    string(1) "1"
    ["especifica"]=>
    string(1) "2"
    ["subespecifica"]=>
    string(1) "0"
    ["costo"]=>
    string(5) "88.50"
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用array_map:

try
{
    var jsonInput = "{success:true,data:'hello', timestamp:'123123123'}"; /*Request at you API*/
    Response response = Newtonsoft.Json.JsonConvert.DeserializeObject<Response>(jsonInput);
}
catch(Exception)
{
    // handle here bad request
}