我怎么能算在一个数组中

时间:2013-10-16 18:15:40

标签: php mysql

撕掉我的头发...如何将以下数组中的数字相加,尝试了这个但是它没有用。我甚至在循环内尝试过它,但我什么都没得到。我认为不应该那么困难,但由于某些原因我无法得到这个。

$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
    )

    )

6 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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'];
}

答案 2 :(得分:1)

试试这个

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

答案 3 :(得分: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'];
}

答案 4 :(得分: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";

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

答案 5 :(得分:0)

计算所有调用的简单方法可以是:

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

这会计算所有项目。