组数组元素并计算价格[关闭]

组数组元素并计算价格[关闭]

问题描述:

Please advice how to group the same elements of array, calculate cost (and total) and output string like:

BBQ - Small (26cm) x 2 - 26.98$

Bolognese - Small (26cm) x 3 - 36$

Coca-cola 0.5 - 1$

....

Total: 120.96$


Array in JSON format:

[{"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"}]

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

烧烤 - 小(26cm)x 2 - 26.98 $ p>

Bolognese - 小(26cm)x 3 - 36 $ p>

可口可乐0.5 - 1 $ p>

.... p>

总计:120.96 $ p>


JSON格式的数组: p>

  [{“name”:“BBQ  -  Small(26cm)”,“params”:“”,“ 价格“:”12.99“},
 {”名称“:”可口可乐0.5“,”参数“:”“,”价格“:”1“},
 {”名称“:”烧烤 - 小(  26厘米)“,”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”},
 {“ 名称“:”烧烤 - 小(26厘米)“,”参数“:”“,”价格“:”12.99“}] 
  code>  pre> 
  div>

Loop the array and build an associative result array.
Add a new item if the item does not exist previously in the array.

Then add 1 to the count and add the price to the subtotal of that item.

$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);

Returns:

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