对数组元素进行分组并计算价格

时间:2019-04-03 07:54:09

标签: php arrays json multidimensional-array

请建议如何对数组的相同元素进行分组,计算成本(和总计)并输出以下字符串:

BBQ-小(26厘米)x 2-26.98美元

肉酱-小(26厘米)x 3-36 $

可口可乐0.5-1美元

....

总计:120.96 $


JSON格式的数组:

[{"name":"BBQ - Small (26cm)","params":"","price":"12.99"},
{"name":"Coca-cola 0.5","params":"","price":"1"},
{"name":"BBQ - Small (26cm)","params":"","price":"12.99"},
{"name":"BBQ - Mid (31cm)","params":"","price":"14.99"},
{"name":"BBQ - Small (26cm)","params":"","price":"12.99"},
{"name":"Bolognese - Small (26cm)","params":"","price":"12"},
{"name":"Coca-cola 0.5","params":"","price":"1"},
{"name":"BBQ - Small (26cm)","params":"","price":"12.99"}]

1 个答案:

答案 0 :(得分:0)

环绕数组并构建关联结果数组。
如果该项目以前不在数组中,则添加一个新项目。

然后将1加到计数并将价格加到该项目的小计中。

$new['total'] =0;

foreach($arr as $sub){
    if(!isset($new[$sub['name']]['count'])){
        $new[$sub['name']]['count'] = 0;
        $new[$sub['name']]['total'] = 0;
    }
    $new[$sub['name']]['count']++;
    $new[$sub['name']]['total'] += $sub['price'];
    $new['total'] += $sub['price'];
}
var_export($new);

返回:

array (
  'total' => 80.95,
  'BBQ - Small (26cm)' => 
  array (
    'count' => 4,
    'total' => 51.96,
  ),
  'Coca-cola 0.5' => 
  array (
    'count' => 2,
    'total' => 2,
  ),
  'BBQ - Mid (31cm)' => 
  array (
    'count' => 1,
    'total' => 14.99,
  ),
  'Bolognese - Small (26cm)' => 
  array (
    'count' => 1,
    'total' => 12,
  ),

https://3v4l.org/JbTf6