PHP:对键相同的子数组的所有值求和

时间:2018-12-06 18:53:30

标签: php mysql json

注意:这不仅是对电话时间的求和,还需要通过PHP函数分别计算电话时间

我目前有以下代码

$i = array(1,2,3,4,5,6,7,8,9,10,11,12);

$j = array();

foreach ($i as $item) {
    $month_query_phonetime = $conn->query("SELECT phone_time FROM bigscreen_daily_data WHERE MONTH(work_date) = {$item} AND YEAR(work_date) = YEAR(CURDATE()) AND user_id = 28");

    while ($dataitem = $month_query_phonetime->fetch_object()) {
        $j[][$item] = point_for_phone_time($dataitem->phone_time);
    }
}

print_r($j);

这给了我如下结果

    Array
    (
        [0] => Array
            (
                [1] => 0
            )

        [1] => Array
            (
                [1] => 10
            )

        [2] => Array
            (
                [2] => 48
            )

        [3] => Array
            (
                [2] => 24
            )

        [4] => Array
            (
                [3] => 48
            )
        [4] => Array
            (
                [3] => 48
            )

    )

我试图将所有[1] => value[2]=> value等的总和作为一个变量,并将其传递给$j[][$item]中的中间项,以便可以将其用于进一步处理

我尝试做

while ($dataitem = $month_query_phonetime->fetch_object()) {
    $m = $m + point_for_phone_time($dataitem->phone_time);
}

$j[][$item] = $m;

它给我的价值如下

Array
(
    [0] => Array
        (
            [1] => {value1}
        )

    [1] => Array
        (
            [2] => {value1+value2}
        )
)

所以为了获得理想的结果,它是处理此问题的正确格式。

3 个答案:

答案 0 :(得分:3)

如果我理解正确,并且您试图将每个phone_time的{​​{1}}求和,为什么不让数据库为您做繁重的工作并使用汇总查询:

user_id

与循环遍历SELECT user_id, SUM(phone_time) AS sum_phone_time FROM bigscreen_daily_data GROUP BY user_id ,查询所有user_id并自己求和相比,它的执行速度也更快。

答案 1 :(得分:0)

让MySQL按月份分组,并将数据集限制为今年:

SELECT   MONTH(work_date) AS m,SUM(phone_time) AS sum_phone_time
FROM     bigscreen_daily_data
WHERE    user_id = 28 AND work_date >= MAKEDATE(year(now()),1);
GROUP BY m

答案 2 :(得分:0)

最终将查询附加到我想要的循环中,现在它显示了预期的结果

foreach ($data as $obj)
{

    $month_query_phonetime = $conn->query("SELECT phone_time FROM bigscreen_daily_data WHERE MONTH(work_date) = {$obj->mon} AND YEAR(work_date) = YEAR(CURDATE()) AND user_id = {$userid} ");

    $m = 0;

    while ($dataitem = $month_query_phonetime->fetch_object()) {
        $m = $m + point_for_phone_time($dataitem->phone_time);
    }

    $obj->prog_point = $obj->prog_point + $m;
}