dongliao3450 2019-04-03 07:54
浏览 50
已采纳

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

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"}]
  • 写回答

1条回答 默认 最新

  • douxi2670 2019-04-03 08:07
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真