In PHP, merge duplicate set of elements of an multidimensional array and sum the values of specific key

前端 未结 1 1804
清歌不尽
清歌不尽 2021-01-26 10:26

I have following array where I am trying to merge the elements which has shelf and weight value as duplicate and sum the value of piece ke

相关标签:
1条回答
  • 2021-01-26 10:52

    If you absolutely have to do this in PHP, then something like:

    $data = array(
        array(
            'shelf' => 'Left',
            'weight' => '10.000',
            'piece' => 1,
        ),
        array(
            'shelf' => 'Right',
            'weight' => '04.000',
            'piece' => 12,
        ),
        array(
            'shelf' => 'Right',
            'weight' => '04.000',
            'piece' => 4,
        ),
        array(
            'shelf' => 'Right',
            'weight' => '07.000',
            'piece' => 8,
        ),
    );
    
    
    $newData = array();
    $result = array_reduce(
        $data,
        function($newData, $value) {
            $key = $value['shelf'].$value['weight'];
            if (!isset($newData[$key])) {
                $newData[$key] = $value;
            } else {
                $newData[$key]['piece'] += $value['piece'];
            }
            return $newData;
        },
        $newData
    );
    var_dump($result);
    

    will work, but I really do believe that you're creating major performance problems for yourself with your whole approach to this problem

    0 讨论(0)
提交回复
热议问题