php - Sum array value per day in multidimensional array

前端 未结 3 427
野的像风
野的像风 2021-01-26 09:52

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

相关标签:
3条回答
  • 2021-01-26 09:54

    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);
    
    0 讨论(0)
  • 2021-01-26 10:04

    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

    0 讨论(0)
  • 2021-01-26 10:10

    You can try this one:

    foreach($myArray as &$value){
        if(is_array($value)){
             $value = array_sum($value);
        }
    }
    
    0 讨论(0)
提交回复
热议问题