我有一个日期和值的数组,例如:
$dates = ['2014-12-01', '2014-12-02', '2014-12-08', '2014-12-09', '2014-12-10', '2014-12-11'];
$values = (5, 3, 7, 8, 9, 2];
您会注意到
12/01
是星期一,12/08
也是星期一。我想按天对这两个数组中的数据进行分组(如果一周):
[
'monday' => [5, 7],
'tuesday' => [3, 8],
'wednesday' => [0, 9],
'thursday' => [0, 2],
]
您会注意到,数组是通过获取与星期几相关的值来形成的。然而,例如,如果星期三日期存在,但前一个星期二不存在,则数组应具有“0”。换句话说,4 个数组的长度应该相同。
注意:到目前为止,我只确定了如何从日期中查找星期几:
date('l', strtotime("2014-12-08"));
我真的想不出解决这个问题的通用算法。
$dates = array( '2014-12-01','2014-12-02','2014-12-08','2014-12-09',
'2014-12-10','2014-12-11' );
$values = array( 5, 3, 7, 8, 9, 2 );
$date = strtotime(min($dates));
$stop = strtotime(max($dates));
$dates = array_flip($dates);
$out = array();
while($date <= $stop)
{
$tmp = date('Y-m-d', $date);
$out[date('l', $date)][] = isset($dates[$tmp]) && isset($values[$dates[$tmp]]) ?
$values[$dates[$tmp]] : 0;
$date = strtotime('+1 day', $date);
}
print_r($out);
结果:
Array
(
[Monday] => Array
(
[0] => 5
[1] => 7
)
[Tuesday] => Array
(
[0] => 3
[1] => 8
)
[Wednesday] => Array
(
[0] => 0
[1] => 9
)
[Thursday] => Array
(
[0] => 0
[1] => 2
)
[Friday] => Array
(
[0] => 0
)
[Saturday] => Array
(
[0] => 0
)
[Sunday] => Array
(
[0] => 0
)
)
ps:
how can I get the an array of all the dates included in the "dates" array associated with only all the Mondays?
修改代码,例如:
$tmp = date('Y-m-d', $date);
$exists = isset($dates[$tmp]) && isset($values[$dates[$tmp]]);
$out[date('l', $date)]['numbers'][] = $exists ? $values[$dates[$tmp]] : 0;
if ($exists) $out[date('l', $date)]['dates'][] = $tmp;
$date = strtotime('+1 day', $date);
您将得到如下输出(以星期一为例)
[Monday] => Array
(
[numbers] => Array
(
[0] => 5
[1] => 7
)
[dates] => Array
(
[0] => 2014-12-01
[1] => 2014-12-08
)
)
可能是一个更好的方法来让
0
进入那里而不需要另一个循环,但我要出去了:
foreach($dates as $key => $val) {
$day = date('l', strtotime($val));
$result[$day][] = $values[$key];
}
foreach($result as &$val) {
if(count($val) == 1) {
array_unshift($val, 0);
}
}
print_r($result);