减少对象数组中的数组

时间:2018-05-29 15:43:50

标签: php laravel

我有这个数组:

Collection {#319 ▼
  #items: array:6 [▼
    "Seccion 1 Pregunta 1" => array:3 [▼
      "satisfactory" => 2
      "unsatisfactory" => 0
      "total" => 2
    ]
    "Seccion 1 Pregunta 2" => array:3 [▼
      "satisfactory" => 2
      "unsatisfactory" => 0
      "total" => 2
    ]
    "Seccion 1 pregunta 3" => array:3 [▼
      "satisfactory" => 0
      "unsatisfactory" => 1
      "total" => 1
    ]
    "Seccion 2 pregunta 1" => array:3 [▼
      "satisfactory" => 3
      "unsatisfactory" => 0
      "total" => 3
    ]
    "Seccion 2 pregunta 2" => array:3 [▼
      "satisfactory" => 1
      "unsatisfactory" => 1
      "total" => 2
    ]
    "Commentarios seccion 2" => array:3 [▼
      "satisfactory" => 0
      "unsatisfactory" => 0
      "total" => 0
    ]
  ]
}

我想得到所有满意,不满意和总价值的总和。类似的东西:

Collection {#319 ▼
    #items: array:3 [▼
          "satisfactory" => 8
          "unsatisfactory" => 2
          "total" => 10
    ]
}

4 个答案:

答案 0 :(得分:3)

如果您知道所需的密钥,请执行以下操作:

[
    'satisfactory'   => $collection->sum('satisfactory'),
    'unsatisfactory' => $collection->sum('unsatisfactory'),
    'total'          => $collection->sum('total')
]

如果你不确定键是什么,请在第一项的键上循环以创建如上所述的类似数组。如果您需要将其作为集合,请执行以下操作:

$newCollection = collect( ... array from above ... );

答案 1 :(得分:2)

您可以尝试以下内容:

$totals = array();
foreach($array as $key => $val) {
    $totals[$key] += $val;
}

答案 2 :(得分:1)

您可以使用array_walk:

$data = [
"Seccion 1 Pregunta 1" => [
  "satisfactory" => 2,
  "unsatisfactory" => 0,
  "total" => 2
],
"Seccion 1 Pregunta 2" => [
  "satisfactory" => 2,
  "unsatisfactory" => 0,
  "total" => 2
],
"Seccion 1 pregunta 3" => [
  "satisfactory" => 0,
  "unsatisfactory" => 1,
  "total" => 1
],
"Seccion 2 pregunta 1" => [
  "satisfactory" => 3,
  "unsatisfactory" => 0,
  "total" => 3
],
"Seccion 2 pregunta 2" => [
  "satisfactory" => 1,
  "unsatisfactory" => 1,
  "total" => 2
],
"Commentarios seccion 2" => [
  "satisfactory" => 0,
  "unsatisfactory" => 0,
  "total" => 0
]
];

$total = array('satisfactory' => 0, 'unsatisfactory' => 0, 'total' => 0);

array_walk($data, function($v) use (&$total) {
   $total['satisfactory'] += $v['satisfactory'];
    $total['unsatisfactory'] += $v['unsatisfactory'];
    $total['total'] += $v['total'];
});

答案 3 :(得分:1)

您也可以使用array_reduce并传递一个数组,其中键和值设置为0作为起始值。

$result = array_reduce($arrays, function($carry, $item){
    $carry["satisfactory"] += $item["satisfactory"];
    $carry["unsatisfactory"] += $item["unsatisfactory"];
    $carry["total"] += $item["total"];
    return $carry;
}, ["satisfactory" => 0, "unsatisfactory" => 0, "total" => 0]);

print_r($result);

那会给你:

Array
(
    [satisfactory] => 8
    [unsatisfactory] => 2
    [total] => 10
)