简体   繁体   中英

php - Sum array value per day in multidimensional array

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.

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

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.

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

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

Here's a demo

You can simply use nested foreach with is_array()

$myArray = array(
    '2014-4-3' => 2,
    '2014-4-4' => 3,
    '2014-4-5' => array(
        0 => 3,
        1 => 7,
        2 => 7,
        3 => 7
    )
);
$new=array();
foreach($myArray as $day=>$value){
    $newval =0;
    if(is_array($value)){
        foreach ($value as $val) {
            $newval += $val;
        }
    }else{
        $newval = $value;
    }
    $new[$day]=$newval;
}

var_dump($new);

You can try this one:

foreach($myArray as &$value){
    if(is_array($value)){
         $value = array_sum($value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM