首页 > 解决方案 > 减少对象数组内的数组

问题描述

我有这个数组:

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
    ]
}

标签: phplaravel

解决方案


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

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

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

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

推荐阅读