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 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果