对数组中的匹配值求和

时间:2012-10-03 09:22:47

标签: php

我目前有以下函数从mssql服务器上的存储过程中提取信息。

我正在尝试制作一个循环,如果团队相同,则汇总所有用户目标。我通常会在mysql中使用一个简单的组和总和来完成此操作但在这里丢失了。

任何对新手的帮助都将不胜感激!

function getSalesPersonTargetTracker()
{
$targetTracker = new StdClass();
$targetTracker->agents = array();

$connection = sqlsrv_connect($server, $connectioninfo);

$query = "{call salespersontargettracker (?)}";
$params = array(
                 date_format(new DateTime(), '01/M/Y')
            );

//Run the Query             
$statement = sqlsrv_query($connection, $query, $params);

if (sqlsrv_fetch($statement) === false)
     print_r( sqlsrv_errors(), true);

//Read in the overall numbers
$targetTracker->target = (float)sqlsrv_get_field($statement, 0);
$targetTracker->workingDays = (int)sqlsrv_get_field($statement, 1);
$targetTracker->currentDay = (int)sqlsrv_get_field($statement, 2);
$targetTracker->dailyTarget = (float)sqlsrv_get_field($statement, 3);
$targetTracker->pointsShouldBeOn = (float)sqlsrv_get_field($statement, 4);
$targetTracker->pointsOn = (float)sqlsrv_get_field($statement, 5);
$targetTracker->pointsDifference = (float)sqlsrv_get_field($statement, 6);
$targetTracker->moneyShouldBeOn = (float)sqlsrv_get_field($statement, 7);
$targetTracker->moneyOn = (float)sqlsrv_get_field($statement, 8);
$targetTracker->moneyDifference = (float)sqlsrv_get_field($statement, 9);

//Move to the next result
sqlsrv_next_result($statement);

//Run through all of the agents and show their details
while (sqlsrv_fetch($statement))
{
    $salesPerson = new StdClass();
    $salesPerson->team = sqlsrv_get_field($statement, 0);
    $salesPerson->username = strtolower(sqlsrv_get_field($statement, 1));
    $salesPerson->target = (float)sqlsrv_get_field($statement, 2);
    $salesPerson->workingDays = (int)sqlsrv_get_field($statement, 3);
    $salesPerson->currentDay = (int)sqlsrv_get_field($statement, 4);
    $salesPerson->dailyTarget = (float)sqlsrv_get_field($statement, 5);
    $salesPerson->pointsShouldBeOn = (float)sqlsrv_get_field($statement, 6);
    $salesPerson->pointsOn = (float)sqlsrv_get_field($statement, 7);
    $salesPerson->pointsDifference = (float)sqlsrv_get_field($statement, 8);
    $salesPerson->moneyShouldBeOn = (float)sqlsrv_get_field($statement, 9);
    $salesPerson->moneyOn = (float)sqlsrv_get_field($statement, 10);
    $salesPerson->moneyDifference = (float)sqlsrv_get_field($statement, 11);

    //Add this person to the people list
    $targetTracker->agents[$salesPerson->moneyOn] = $salesPerson;
    krsort($targetTracker->agents);
}

return $targetTracker;
}

 $targetTrackerall = getSalesPersonTargetTracker();

1 个答案:

答案 0 :(得分:0)

在第二个循环中,您可以在最后添加此代码。

if (!isset($sums[$salesPerson->team])) {
    $sums[$salesPerson->team] = 0;
}
$sums[$salesPerson->team] += $salesPerson->target;

它构建一个数组,其中团队作为关键点,以及该团队中任何人的目标总和。循环结束后,您可以使用$sums

的值

如果这不起作用,请告诉我var_dump($sums)的价值。