0

扯掉我的头发......如何对以下数组中的数字求和,尝试了这个,但它没有用。我什至在循环内尝试过,但我什么也没得到。我不认为它应该那么困难,但由于某种原因我无法得到这个。

$sql = "SELECT queue_name,type,COUNT(uniqueid) AS calls FROM CallLog WHERE start_time     BETWEEN '2013-10-14 00:00:00' AND '2013-10-14 23:59:59' GROUP BY queue_name, type";

$stmt=$dbh->prepare($sql);
$stmt->execute();

$calls = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach($calls as $call){
$results[ $call['queue_name'] ][ $call['type'] ] = $call['calls'];

}

$totalCalls = array_sum($call['calls']);

echo '<pre>';
print_r($results);
echo '</pre>';
echo $totalCalls;
?>
Array
    (
    [Escalations] => Array
    (
        [abandoned] => 2
        [completed] => 3
        [redirected] => 1
    )

[Premium] => Array
    (
        [abandoned] => 7
        [completed] => 29
        [redirected] => 6
    )

[Standard] => Array
    (
        [abandoned] => 14
        [completed] => 41
        [redirected] => 53
    )

[Wingate Queue] => Array
    (
        [abandoned] => 2
        [completed] => 3
    )

[WorldMark] => Array
    (
        [abandoned] => 32
        [completed] => 100
        [redirected] => 82
    )

    )
4

6 回答 6

2
<?php
$results = array(
    'Escalations' => array('abandoned' => 2,'completed' => 3,'redirected' => 1),
    'Premium' => array('abandoned' => 7,'completed' => 29,'redirected' => 6),
    'Standard' => array('abandoned' => 14,'completed' => 41,'redirected' => 53),
    'Wingate Queue' => array('abandoned' => 2,'completed' => 3),
    'WorldMark' => array('abandoned' => 32,'completed' => 100,'redirected' => 82)
);

$total_calls = 0;
foreach($results as $k=>$v){
    $total_calls += array_sum($v);
}

echo $total_calls;
于 2013-10-16T18:23:41.560 回答
1

$call未在for循环之外定义:

$totalCalls = array_sum($call['calls']);
                        ^^^^^

你可以在循环中总结它:

$totalCalls = 0;
foreach($calls as $call){
    $results[ $call['queue_name'] ][ $call['type'] ] = $call['calls'];
    $totalCalls += $call['calls'];
}
于 2013-10-16T18:20:51.940 回答
1

试试这个

$totalCalls = 0;
foreach($calls as $call){
    $results[ $call['queue_name'] ][ $call['type'] ] = $call['calls'];
    $totalCalls += $call['calls'];
}
于 2013-10-16T18:21:53.383 回答
1

您的代码中有一个错误:

    $totalCalls = array_sum($call['calls']); 
// $call['calls'] is just a single value not an array

最简单的方法是:

$totalCalls = 0;
foreach($calls as $call){
$results[ $call['queue_name'] ][ $call['type'] ] = $call['calls'];
$totalCalls += $call['calls'];
}
于 2013-10-16T18:22:09.960 回答
1

如果您不需要其他地方的其余数据,您可以在 SQL 查询中执行此操作。

类似于以下内容:

SELECT 
    SUM(uniqueid) AS total
FROM 
    CallLog 
WHERE
    start_time BETWEEN '2013-10-14 00:00:00' AND '2013-10-14 23:59:59'
GROUP BY 
    queue_name, type";

请记住,这将返回一个数字,而不是您之前拥有的所有数据。

于 2013-10-16T18:27:24.540 回答
0

计算所有调用的一种更简单的方法是:

$totalCalls = 0;
foreach($calls as $call){
    $totalCalls += array_sum($call);
}

这将计算所有项目。

于 2013-10-16T19:12:05.640 回答