php-多维数组中每天的数组总和 [英] php - Sum array value per day in multidimensional array

查看:101
本文介绍了php-多维数组中每天的数组总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Stackoverflow上有很多关于如何对多维关联数组求和的很棒的问答,但我还没有找到在多维多维数组中进行小计的有效示例.

There are a number of great Q&As on Stackoverflow on how to sum across a multidimensional associative array but I have not found a working example of doing subtotals within a multidimensional one.

例如,我有一个数据以这种形状从mysql查询数据输出到php中:

For instance I have data coming out of a mysql query into php with this shape:

$myArray = array(
    '2014-4-3' => 2,
    '2014-4-4' => 3,
    '2014-4-5' => array(
        0 => 3,
        1 => 7,
        2 => 7,
        3 => 7
    )
);

从本质上讲,我每天都在拉高餐馆的收视率.某些日子可能会有很多评分,而其他日子可能会更少(阵列中省略没有评分的日子).在具有更多收视率的日子里,我想总结该天的总数,因此一个新的数组将简单地如下所示:

Essentially, I am pulling the ratings made of restaurants by day. Some days might have many ratings and others will have fewer (those days with no ratings are omitted from the array). On days with more ratings I would like to sum up to a total for that given day so a new array would look simply as follows:

'2014-4-3' => 2
'2014-4-4' => 3
'2014-4-5' => 24

我已经尝试了数小时来破解发布的用于求和多维数组的foreach和函数方法,但到目前为止还没有.一个关键问题是,由于每天添加的日期本身并不事先知道,因此必须扩展相同的过程.

I have tried for hours to hack the foreach and functions approaches posted for summing multidimensional arrays but nothing so far. One key problem is that the days themselves aren't known in advance as each day is added the same process must be expanded.

推荐答案

您可以使用 array_map()

You could do this using array_map() and array_sum():

$output = array_map(function($a) { 
    return is_array($a) ? array_sum($a) : $a; 
}, $myArray);

这篇关于php-多维数组中每天的数组总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆