数组循环和求和键

时间:2012-03-13 05:43:28

标签: php

我正在尝试将每个工作日的密钥[0]中的所有值相加(密钥[1])。最后一个数组应该包含一周中的每一天和相关的总和(或只是一个值)。

Array ( 
[404045862944400] => Array ( 
[0] => 192 
[1] => 23:52,Monday 
) 
[403274909688162] => Array ( 
[0] => 186 
[1] => 22:21,Tuesday 
) 
[402735273075459] => Array ( 
[0] => 336 
[1] => 04:29,Wednesday 
) 
[252948031457462] => Array ( 
[0] => 410 
[1] => 06:22,Thursday 
) 
[400606749954978] => Array ( 
[0] => 312 
[1] => 05:01,Saturday 
) 
[286755318061725] => Array ( 
[0] => 384 
[1] => 04:51,Friday 
) 
[399687880046865] => Array ( 
[0] => 257 
[1] => 21:51,Sunday 
) 
[398332190182434] => Array ( 
[0] => 240 
[1] => 23:19,Tuesday 
) 
[397768486905471] => Array ( 
[0] => 311 
[1] => 05:38,Friday 
) 
)

以下是我正在使用的内容:

$days = array();

foreach($content_arr as $v_days) { 

   $dayKey= array_shift(explode(',', $v_days[1]));

   if(!array_key_exists($dayKey, $days)) $days[$dayKey] = 0;
   $days[$dayKey] += $v_days[0];
  }

这给出了按键[1]中的时间值而不是工作日的细分:

Array ( 
[23:52] => 192 
[22:21] => 186 
[04:29] => 336 
[06:22] => 410 
[05:01] => 312 
[04:51] => 886 
[21:51] => 257 
[23:19] => 240 
[05:38] => 311 
[03:38] => 293 
[05:12] => 496 
[04:15] => 475 
[04:01] => 488 
[03:44] => 506 
[06:05] => 917 
[04:00] => 452 
[04:13] => 525 
[00:22] => 415 
[01:10] => 372 
)

1 个答案:

答案 0 :(得分:1)

以下应该适合你:

$content_arr = array('404045862944400' => array(192,'23:52,Monday'),
                     '403274909688162' => array(186,'21:52,Tuesday'),
                     '402735273075459' => array(8,'22:52,Monday')
                    );

$days = array();
foreach($content_arr as $v_days) {   
   $arr = explode(',', $v_days[1]);
   $days[$arr[1]] += $v_days[0];
}

print_r($days);

<强>输出:

Array
(
    [Monday] => 200
    [Tuesday] => 186
)