How to sum array value of duplicate data

前端 未结 5 1351
滥情空心
滥情空心 2020-12-20 01:41

I have an array with some of same ID value as shown in below.

[
    {\"ID\":\"126871\",\"total\":\"200.00\",\"currency\":\"USD\",\"name\":\"John         


        
5条回答
  •  时光说笑
    2020-12-20 02:17

    @Cloud I have made function for your requirement and Thanks @M. I. for look into this sum section.

    $array = array(
        array("ID"  => "126871","total"=>"200.00","currency"=>"USD","name"=>"John"),
        array("ID"  => "126872","total"=>"2000.00","currency"=>"Euro","name"=>"John"),
        array("ID"  => "126872","total"=>"1000.00","currency"=>"Euro","name"=>"John"),
        array("ID"  => "126872","total"=>"500.00","currency"=>"USD","name"=>"John"),
        array("ID"  => "126872","total"=>"1000.00","currency"=>"Euro","name"=>"John"),
    );
    echo "
    ";
    print_r($array);
    
    function unique_multidim_array($array, $key,$key1,$addedKey) { 
        $temp_array = array(); 
        $i = 0; 
        $key_array = array(); 
        $key1_array = array(); 
    
        foreach($array as $val) { 
            if (!in_array($val[$key], $key_array) && !in_array($val[$key1], $key1_array)) { 
                $key_array[$i] = $val[$key]; 
                $key1_array[$i] = $val[$key1]; 
                $temp_array[$i] = $val; 
            }else{
                $pkey = array_search($val[$key],$key_array);
                $pkey1 = array_search($val[$key1],$key1_array);
                if($pkey==$pkey1){
                    $temp_array[$pkey][$addedKey] += $val[$addedKey];
                }else{
                    $key_array[$i] = $val[$key]; 
                    $key1_array[$i] = $val[$key1]; 
                    $temp_array[$i] = $val; 
                }
                // die;
            }
            $i++; 
        } 
        return $temp_array; 
    } 
    
    $nArray = unique_multidim_array($array,"ID","currency","total");
    // die;
    print_r($nArray);
    die;
    

提交回复
热议问题