PHP数组总和由相同的键值对需要计算

时间:2016-09-23 08:51:33

标签: php arrays

<?php 
error_reporting(E_ALL);
$test_array = Array(Array
(
    "pid" => 1,
    "encounter" => 20,
    "code" => abc,
    "fee" => 300.00
),
Array
(
    "pid" => 1,
    "encounter" => 20,
    "code" => abc,
    "fee" => 300.00
),
Array
(
    "pid" => 2,
    "encounter" => 20,
    "code" => abc,
    "fee" => 80
),
Array
(
    "pid" => 3,
    "encounter" => 20,
    "code" => xyz,
    "fee" => 90
),
Array
(
    "pid" => 5,
    "encounter" => 40,
    "code" => xyz,
    "fee" => 100
),
Array
(
    "pid" => 3,
    "encounter" => 40,
    "code" => xyz,
    "fee" => 100
),
Array
(
    "pid" => 2,
    "encounter" => 20,
    "code" => abc,
    "fee" => 80
),
Array
(
    "pid" => 1,
    "encounter" => 20,
    "code" => xyz,
    "fee" => 40
));
//Declaration...
$pre_pid = "";
$pre_encounter = "";
$pre_code = "";
$pre_fee = "";
$sum_charges = 0;
/*Foreach loop*/
$i=0;
foreach($test_array as $my_arr){
    $pre_pid = $my_arr['pid'];
    $pre_encounter = $my_arr['encounter'];
    $pre_code = $my_arr['code'];
    if($pre_pid == $my_arr['pid'] && $pre_encounter == $my_arr['encounter'] && $pre_code == $my_arr['code']){
        echo "FEE-AMOUNT=".$my_arr['fee'];
        $sum_charges+=$my_arr['fee'];
        echo '<br/>';
    }
$i++;
}
//Getting Sum = 1090
//Actual Sum I needed = 710
?>

你好朋友我正在尝试上面的代码,我想要费用应该计算那些拥有相同3键值对的人。 例如,如果每个数组3的键值相同,则仅计算这些费用金额。

1 个答案:

答案 0 :(得分:0)

如果我理解了您的问题,那么每当其他3列具有相同的值时,您需要对费用列求和。我对您的代码进行了一些自定义,以便您可以获得每个元素的总成本。

//Declaration...
$pre_pid = "";
$pre_encounter = "";
$pre_code = "";
$pre_fee = "";
$sum_charges = 0;
$sum_array = array();
$total_fees = 0;
/*Foreach loop*/

foreach($test_array as &$my_arr){

    $pre_pid = $my_arr['pid'];
    $pre_encounter = $my_arr['encounter'];
    $pre_code = $my_arr['code'];
    $pre_fee = $my_arr['fee'];
    $fee_ammount = $pre_fee;
    $duplicates_check = array();

    foreach($test_array as $value) {
        if($pre_pid == $value['pid'] && ($pre_encounter != $value['encounter'] || $pre_code != $value['code'])){

            $duplicate = false;

            foreach($duplicates_check as $duplicate_array) {
                if($duplicate_array == $value)
                    $duplicate =true;
            }
            if(!$duplicate) {
                $fee_ammount += $value['fee'];
                $duplicates_check[] = $value;
            }
        }
    }
    $my_arr['total_fee'] = $fee_ammount;

    if(!isset($sum_array[$my_arr['pid']])) {
        $sum_array[$my_arr['pid']] = $my_arr['total_fee'];
        echo 'pid => '.$my_arr['pid'].', total fees => '.$my_arr['total_fee'].'<br />';
        $total_fees += $my_arr['total_fee'];
    }
}

echo 'Total : '.$total_fees;
var_dump($sum_array);