php - Sum array value per day in multidimensional array

前端 未结 3 428
野的像风
野的像风 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);
    

提交回复
热议问题