douyi1084 2018-07-25 03:35
浏览 42
已采纳

数组和组中的产品价格总和

i have this JSON array i decode into a PHP array and would like to check how much have been sold in total in each category

    [{
        "categorycode": "W0000000391",           
        "grosssalesprice": "50.00"
    },
    {
        "categorycode": "W0000000396",
        "grosssalesprice": "170.00"
    },
    {
        "categorycode": "W0000000391",
        "grosssalesprice": "50.00"
    },
    {            
        "categorycode": "W0000000391",
        "grosssalesprice": "55.00"
    }]

and would like to get

{
    "categorycode": "W0000000391",           
    "grosssalesprice": "155.00"
},
{
    "categorycode": "W0000000396",
    "grosssalesprice": "170.00"
}

I tried, this gives me 1 entry foreach element, but how do i append every item in this array?

foreach($jsonDecoded as $item) {            
            $sortedData[$item['categorycode']] = array(
            'Konto' => $item['categorycode'],
            'Beløb' => $item['grosssalesprice']
            );          
        }

展开全部

  • 写回答

1条回答 默认 最新

  • dongyo1818 2018-07-25 03:41
    关注
    $items = json_decode($json,true);
    foreach($items as $item){
        if(empty($totalInCategory[$item['categorycode']])){
            $totalInCategory[$item['categorycode']] = 0.00;
        }
        $totalInCategory[$item['categorycode']] += $item['grosssalesprice'];
    }
    var_dump($totalInCategory);
    

    Should do it, and present:

    array(2) {
      ["W0000000391"]=>
      float(155)
      ["W0000000396"]=>
      float(170)
    }
    

    But, to match your required format more:

    foreach($items as $item){
        if(empty($totalInCategory[$item['categorycode']]['grosssalesprice'])){
            $totalInCategory[$item['categorycode']]['grosssalesprice'] = 0.00;
        }
        $totalInCategory[$item['categorycode']]['categorycode'] = $item['categorycode'];
        $totalInCategory[$item['categorycode']]['grosssalesprice'] += $item['grosssalesprice'];
    } 
    

    But keys need to be unique, so you can leave them like this or run a sort() on the resulting array to reset the array keys to the integer values

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部