在 laravel 刀片模板中,我试图减少这样的数组:
$longList = [['box' => 1, 'kg' => 2], ['box' => 2, 'kg' => 2], ['box' => 3, 'kg' => 3]];
变成这样的东西:
$reducedList = [['count' => 2, 'kg' => 2], ['count' => 1, 'kg' => 3]];
这是我到目前为止所拥有的:
@php
$variableWeights = isset($sale->variable_weight_json) ? collect(json_decode($sale->variable_weight_json, true)) : null;
$groups = array();
if (isset($variableWeights)) {
$groups = $variableWeights->reduce(function($carry, $item) {
$index = array_search($item['kg'], array_column($carry, 'weight'));
if (isset($index)) {
$existing = $carry[$index];
array_splice($carry, $index, 1, [
'count' => $existing['count'] + 1,
'weight' => $item['kg']
]);
} else {
array_push($carry, [
'count' => 1,
'weight' => $item['kg'],
]);
}
return $carry;
}, array());
}
@endphp
但它给了我错误 Undefined offset: 0
我是 php 新手。应该如何更正代码或者是否有更好的方法来达到预期的结果?